Skip to content

Commit c361cd0

Browse files
committed
Refactor code for improved readability and performance
- Updated file reading methods in DropboxFolderCopyReader and DropboxFileCopyReader to use context managers without explicit mode. - Removed unnecessary future import in parse_format.py. - Simplified string formatting using f-strings in multiple classes within parse_format.py. - Replaced old-style class definitions with new-style in various utility classes. - Optimized recursive directory iteration functions in local_files.py using yield from. - Enhanced type hinting in w_helpful_folder_not_found_error function. - Streamlined zip function usage in mk_kv_from_keygen. - Updated glom.py to use f-strings for better readability in error messages and representations. - Changed type imports to use collections.abc for better compatibility. - Refactored mongoquery.py to utilize f-strings for error messages. - Minor adjustments in tests/utils_for_testing.py for clarity in user prompts.
1 parent 0f41b2e commit c361cd0

File tree

11 files changed

+135
-134
lines changed

11 files changed

+135
-134
lines changed

misc/best of 2020 demo.ipynb

Lines changed: 38 additions & 34 deletions
Large diffs are not rendered by default.

py2store/examples/dropbox_w_urllib.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ def __init__(self, url, path=tempfile.gettempdir()):
2222
def __getitem__(self, rel_path):
2323
real_path = os.path.join(self.path, rel_path)
2424
try:
25-
with open(real_path, 'r') as f:
25+
with open(real_path) as f:
2626
return f.read()
2727
except FileNotFoundError:
2828
raise KeyError(f"Key doesn't exist: {rel_path}")
@@ -50,7 +50,7 @@ def __init__(self, url, path=None):
5050
self.path = path or self._get_filename_from_url()
5151

5252
download_from_dropbox(self.url, self.path)
53-
self.file = open(self.path, 'r')
53+
self.file = open(self.path)
5454

5555
def __getitem__(self, index):
5656
self.file.seek(0)

py2store/parse_format.py

Lines changed: 20 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -401,7 +401,6 @@
401401
See the end of the source file for the license of use.
402402
"""
403403

404-
from __future__ import absolute_import
405404

406405
__version__ = '1.9.0'
407406

@@ -500,7 +499,7 @@ def __init__(self, offset, name):
500499
self._name = name
501500

502501
def __repr__(self):
503-
return '<%s %s %s>' % (self.__class__.__name__, self._name, self._offset,)
502+
return '<{} {} {}>'.format(self.__class__.__name__, self._name, self._offset)
504503

505504
def utcoffset(self, dt):
506505
return self._offset
@@ -708,7 +707,7 @@ def extract_format(format, extra_types):
708707
PARSE_RE = re.compile(r'''({{|}}|{\w*(?:(?:\.\w+)|(?:\[[^\]]+\]))*(?::[^}]+)?})''')
709708

710709

711-
class Parser(object):
710+
class Parser:
712711
"""Encapsulate a format string that may be used to parse other strings."""
713712

714713
def __init__(self, format, extra_types=None, case_sensitive=False):
@@ -744,8 +743,8 @@ def __init__(self, format, extra_types=None, case_sensitive=False):
744743

745744
def __repr__(self):
746745
if len(self._format) > 20:
747-
return '<%s %r>' % (self.__class__.__name__, self._format[:17] + '...',)
748-
return '<%s %r>' % (self.__class__.__name__, self._format)
746+
return '<{} {!r}>'.format(self.__class__.__name__, self._format[:17] + '...')
747+
return '<{} {!r}>'.format(self.__class__.__name__, self._format)
749748

750749
@property
751750
def _search_re(self):
@@ -880,7 +879,7 @@ def evaluate_result(self, m):
880879
named_fields[korig] = value
881880

882881
# now figure the match spans
883-
spans = dict((n, m.span(name_map[n])) for n in named_fields)
882+
spans = {n: m.span(name_map[n]) for n in named_fields}
884883
spans.update((i, m.span(n + 1)) for i, n in enumerate(self._fixed_fields))
885884

886885
# and that's our result
@@ -921,7 +920,7 @@ def _to_group_name(self, field):
921920
elif '_' in field:
922921
group = field.replace('_', '_' * n)
923922
else:
924-
raise KeyError('duplicated group name %r' % (field,))
923+
raise KeyError('duplicated group name {!r}'.format(field))
925924

926925
# save off the mapping
927926
self._group_to_name_map[group] = field
@@ -1034,7 +1033,7 @@ def f(string, m):
10341033
)
10351034
self._group_index += 7
10361035
elif type == 'tg':
1037-
s = r'(\d{1,2}[-/](\d{1,2}|%s)[-/]\d{4})(\s+%s)?%s?%s?' % (
1036+
s = r'(\d{{1,2}}[-/](\d{{1,2}}|{})[-/]\d{{4}})(\s+{})?{}?{}?'.format(
10381037
ALL_MONTHS_PAT,
10391038
TIME_PAT,
10401039
AM_PAT,
@@ -1046,7 +1045,7 @@ def f(string, m):
10461045
)
10471046
self._group_index += 9
10481047
elif type == 'ta':
1049-
s = r'((\d{1,2}|%s)[-/]\d{1,2}[-/]\d{4})(\s+%s)?%s?%s?' % (
1048+
s = r'((\d{{1,2}}|{})[-/]\d{{1,2}}[-/]\d{{4}})(\s+{})?{}?{}?'.format(
10501049
ALL_MONTHS_PAT,
10511050
TIME_PAT,
10521051
AM_PAT,
@@ -1059,7 +1058,7 @@ def f(string, m):
10591058
self._group_index += 9
10601059
elif type == 'te':
10611060
# this will allow microseconds through if they're present, but meh
1062-
s = r'(%s,\s+)?(\d{1,2}\s+%s\s+\d{4})\s+%s%s' % (
1061+
s = r'({},\s+)?(\d{{1,2}}\s+{}\s+\d{{4}})\s+{}{}'.format(
10631062
DAYS_PAT,
10641063
MONTHS_PAT,
10651064
TIME_PAT,
@@ -1072,14 +1071,14 @@ def f(string, m):
10721071
self._group_index += 8
10731072
elif type == 'th':
10741073
# slight flexibility here from the stock Apache format
1075-
s = r'(\d{1,2}[-/]%s[-/]\d{4}):%s%s' % (MONTHS_PAT, TIME_PAT, TZ_PAT,)
1074+
s = r'(\d{{1,2}}[-/]{}[-/]\d{{4}}):{}{}'.format(MONTHS_PAT, TIME_PAT, TZ_PAT)
10761075
n = self._group_index
10771076
self._type_conversions[group] = partial(
10781077
date_convert, dmy=n + 1, hms=n + 3, tz=n + 6
10791078
)
10801079
self._group_index += 6
10811080
elif type == 'tc':
1082-
s = r'(%s)\s+%s\s+(\d{1,2})\s+%s\s+(\d{4})' % (
1081+
s = r'({})\s+{}\s+(\d{{1,2}})\s+{}\s+(\d{{4}})'.format(
10831082
DAYS_PAT,
10841083
MONTHS_PAT,
10851084
TIME_PAT,
@@ -1090,7 +1089,7 @@ def f(string, m):
10901089
)
10911090
self._group_index += 8
10921091
elif type == 'tt':
1093-
s = r'%s?%s?%s?' % (TIME_PAT, AM_PAT, TZ_PAT)
1092+
s = r'{}?{}?{}?'.format(TIME_PAT, AM_PAT, TZ_PAT)
10941093
n = self._group_index
10951094
self._type_conversions[group] = partial(
10961095
date_convert, hms=n + 1, am=n + 4, tz=n + 5
@@ -1108,7 +1107,7 @@ def f(string, m):
11081107
s = r'\%s+' % type
11091108
elif format.get('precision'):
11101109
if format.get('width'):
1111-
s = '.{%s,%s}?' % (format['width'], format['precision'])
1110+
s = '.{{{},{}}}?'.format(format['width'], format['precision'])
11121111
else:
11131112
s = '.{1,%s}?' % format['precision']
11141113
elif format.get('width'):
@@ -1154,16 +1153,16 @@ def f(string, m):
11541153

11551154
# align "=" has been handled
11561155
if align == '<':
1157-
s = '%s%s*' % (s, fill)
1156+
s = '{}{}*'.format(s, fill)
11581157
elif align == '>':
1159-
s = '%s*%s' % (fill, s)
1158+
s = '{}*{}'.format(fill, s)
11601159
elif align == '^':
1161-
s = '%s*%s%s*' % (fill, s, fill)
1160+
s = '{}*{}{}*'.format(fill, s, fill)
11621161

11631162
return s
11641163

11651164

1166-
class Result(object):
1165+
class Result:
11671166
"""The result of a parse() or search().
11681167
11691168
Fixed results may be looked up using result[index]. Named results may be
@@ -1181,10 +1180,10 @@ def __getitem__(self, item):
11811180
return self.named[item]
11821181

11831182
def __repr__(self):
1184-
return '<%s %r %r>' % (self.__class__.__name__, self.fixed, self.named)
1183+
return '<{} {!r} {!r}>'.format(self.__class__.__name__, self.fixed, self.named)
11851184

11861185

1187-
class Match(object):
1186+
class Match:
11881187
"""The result of a parse() or search() if no results are generated.
11891188
11901189
This class is only used to expose internal used regex match objects
@@ -1200,7 +1199,7 @@ def evaluate_result(self):
12001199
return self.parser.evaluate_result(self.match)
12011200

12021201

1203-
class ResultIterator(object):
1202+
class ResultIterator:
12041203
"""The result of a findall() operation.
12051204
12061205
Each element is a Result instance.

py2store/persisters/local_files.py

Lines changed: 8 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -89,10 +89,9 @@ def iter_filepaths_in_folder_recursively(
8989
for full_path in paths_in_dir(root_folder):
9090
if os.path.isdir(full_path):
9191
if _current_level < max_levels:
92-
for entry in iter_filepaths_in_folder_recursively(
92+
yield from iter_filepaths_in_folder_recursively(
9393
full_path, max_levels, _current_level + 1
94-
):
95-
yield entry
94+
)
9695
else:
9796
if os.path.isfile(full_path):
9897
yield full_path
@@ -105,10 +104,9 @@ def iter_dirpaths_in_folder_recursively(root_folder, max_levels=None, _current_l
105104
if os.path.isdir(full_path):
106105
yield full_path
107106
if _current_level < max_levels:
108-
for entry in iter_dirpaths_in_folder_recursively(
107+
yield from iter_dirpaths_in_folder_recursively(
109108
full_path, max_levels, _current_level + 1
110-
):
111-
yield entry
109+
)
112110

113111

114112
class PrefixedFilepaths:
@@ -214,13 +212,14 @@ def first_non_existing_parent_dir(dirpath):
214212
# Local File Persistence : Classes
215213

216214
from functools import wraps
217-
from typing import Union, Callable
215+
from typing import Union
216+
from collections.abc import Callable
218217

219218

220219
def w_helpful_folder_not_found_error(
221220
*,
222221
raise_error=KeyError,
223-
extra_msg: Union[str, Callable] = '',
222+
extra_msg: str | Callable = '',
224223
caught_errors=FileNotFoundError,
225224
):
226225
if isinstance(extra_msg, str):
@@ -237,7 +236,7 @@ def wrapped_method(*args, **kwargs):
237236
try:
238237
return method(*args, **kwargs)
239238
except caught_errors as e:
240-
msg = '{}: {}\n'.format(type(e).__name__, e) + extra_msg(
239+
msg = f'{type(e).__name__}: {e}\n' + extra_msg(
241240
*args, **kwargs
242241
)
243242
raise raise_error(msg)

py2store/utils/affine_conversion.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
"""
44

55

6-
class AffineConverter(object):
6+
class AffineConverter:
77
"""
88
Getting a callable that will perform an affine conversion.
99
Note, it does it as

py2store/utils/cache_descriptors.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@
2323
ncaches = 0
2424

2525

26-
class _CachedProperty(object):
26+
class _CachedProperty:
2727
"""
2828
Cached property implementation class.
2929
"""
@@ -92,7 +92,7 @@ def factory(function):
9292
return factory
9393

9494

95-
class Lazy(object):
95+
class Lazy:
9696
"""Lazy Attributes."""
9797

9898
def __init__(self, func, name=None):
@@ -111,7 +111,7 @@ def __get__(self, inst, class_):
111111
return value
112112

113113

114-
class readproperty(object):
114+
class readproperty:
115115
def __init__(self, func):
116116
self.func = func
117117
update_wrapper(self, func)
@@ -124,7 +124,7 @@ def __get__(self, inst, class_):
124124
return func(inst)
125125

126126

127-
class cachedIn(object):
127+
class cachedIn:
128128
"""Cached property with given cache attribute."""
129129

130130
def __init__(self, attribute_name):

py2store/utils/cumul_aggreg_write.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -41,8 +41,7 @@ def join_string_values_and_key_as_current_utc_milliseconds(gen):
4141

4242
def mk_kv_from_keygen(keygen=itertools.count()):
4343
def aggregate(gen):
44-
for k, v in zip(keygen, gen):
45-
yield k, v
44+
yield from zip(keygen, gen)
4645

4746
return aggregate
4847

0 commit comments

Comments
 (0)