Skip to content

Commit 026b5d2

Browse files
committed
linted
1 parent d5124cc commit 026b5d2

File tree

3 files changed

+187
-152
lines changed

3 files changed

+187
-152
lines changed

upath/core.py

Lines changed: 100 additions & 63 deletions
Original file line numberDiff line numberDiff line change
@@ -15,64 +15,84 @@
1515

1616

1717
class _FSSpecAccessor:
18-
1918
def __init__(self, parsed_url, *args, **kwargs):
2019
self._url = parsed_url
2120
cls = get_filesystem_class(self._url.scheme)
22-
url_kwargs = cls._get_kwargs_from_urls(urllib.parse.urlunparse(self._url))
21+
url_kwargs = cls._get_kwargs_from_urls(
22+
urllib.parse.urlunparse(self._url)
23+
)
2324
url_kwargs.update(kwargs)
2425
self._fs = cls(**url_kwargs)
25-
if self._url.scheme in ['hdfs']:
26-
self._fs.root_marker = '/'
27-
26+
if self._url.scheme in ["hdfs"]:
27+
self._fs.root_marker = "/"
2828

2929
def argument_upath_self_to_filepath(self, func):
30-
'''if arguments are passed to the wrapped function, and if the first
30+
"""if arguments are passed to the wrapped function, and if the first
3131
argument is a UniversalPath instance, that argument is replaced with
3232
the UniversalPath's path attribute
33-
'''
33+
"""
34+
3435
def wrapper(*args, **kwargs):
3536
if args:
3637
args = list(args)
3738
first_arg = args.pop(0)
38-
if not kwargs.get('path'):
39+
if not kwargs.get("path"):
3940
if isinstance(first_arg, UniversalPath):
4041
first_arg = first_arg.path
41-
if not self._fs.root_marker and first_arg.startswith('/'):
42+
if not self._fs.root_marker and first_arg.startswith(
43+
"/"
44+
):
4245
first_arg = first_arg[1:]
4346
args.insert(0, first_arg)
4447
args = tuple(args)
4548
else:
46-
if not self._fs.root_marker and kwargs['path'].startswith('/'):
47-
kwargs['path'] = kwargs['path'][1:]
48-
if self._url.scheme == 'hdfs':
49-
if 'trunicate' in kwargs:
50-
kwargs.pop('trunicate')
51-
if func.__name__ == 'mkdir':
49+
if not self._fs.root_marker and kwargs["path"].startswith(
50+
"/"
51+
):
52+
kwargs["path"] = kwargs["path"][1:]
53+
if self._url.scheme == "hdfs":
54+
if "trunicate" in kwargs:
55+
kwargs.pop("trunicate")
56+
if func.__name__ == "mkdir":
5257
args = args[:1]
53-
58+
5459
return func(*args, **kwargs)
60+
5561
return wrapper
5662

5763
def __getattribute__(self, item):
58-
class_attrs = ['_url', '_fs']
64+
class_attrs = ["_url", "_fs"]
5965
if item in class_attrs:
6066
x = super().__getattribute__(item)
6167
return x
62-
class_methods =['__init__', '__getattribute__', 'argument_upath_self_to_filepath']
68+
class_methods = [
69+
"__init__",
70+
"__getattribute__",
71+
"argument_upath_self_to_filepath",
72+
]
6373
if item in class_methods:
64-
return lambda *args, **kwargs: getattr(_FSSpecAccessor, item)(self, *args, **kwargs)
65-
if item == '__class__':
74+
return lambda *args, **kwargs: getattr(_FSSpecAccessor, item)(
75+
self, *args, **kwargs
76+
)
77+
if item == "__class__":
6678
return _FSSpecAccessor
6779
d = object.__getattribute__(self, "__dict__")
68-
fs = d.get('_fs', None)
80+
fs = d.get("_fs", None)
6981
if fs is not None:
7082
method = getattr(fs, item, None)
7183
if method:
72-
awaitable = inspect.isawaitable(lambda args, kwargs: method(*args, **kwargs))
73-
return lambda *args, **kwargs: self.argument_upath_self_to_filepath(method)(*args, **kwargs)
84+
awaitable = inspect.isawaitable(
85+
lambda args, kwargs: method(*args, **kwargs)
86+
)
87+
return lambda *args, **kwargs: self.argument_upath_self_to_filepath(
88+
method
89+
)(
90+
*args, **kwargs
91+
)
7492
else:
75-
raise NotImplementedError(f'{fs.protocol} filesystem has not attribute {item}')
93+
raise NotImplementedError(
94+
f"{fs.protocol} filesystem has not attribute {item}"
95+
)
7696

7797

7898
class PureUniversalPath(PurePath):
@@ -81,32 +101,32 @@ class PureUniversalPath(PurePath):
81101

82102

83103
class UPath(pathlib.Path):
84-
85104
def __new__(cls, *args, **kwargs):
86105
if cls is UPath:
87106
new_args = list(args)
88107
first_arg = new_args.pop(0)
89108
parsed_url = urllib.parse.urlparse(first_arg)
90-
for key in ['scheme', 'netloc']:
109+
for key in ["scheme", "netloc"]:
91110
val = kwargs.get(key)
92111
if val:
93112
parsed_url._replace(**{key: val})
94113
if not parsed_url.scheme:
95-
cls = WindowsPath if os.name == 'nt' else PosixPath
114+
cls = WindowsPath if os.name == "nt" else PosixPath
96115
else:
97116
cls = UniversalPath
98117
# cls._url = parsed_url
99-
kwargs['_url'] = parsed_url
118+
kwargs["_url"] = parsed_url
100119
new_args.insert(0, parsed_url.path)
101120
args = tuple(new_args)
102-
121+
103122
if cls is UniversalPath:
104123
self = cls._from_parts_init(args, init=False)
105124
else:
106125
self = cls._from_parts(args, init=False)
107126
if not self._flavour.is_supported:
108-
raise NotImplementedError("cannot instantiate %r on your system"
109-
% (cls.__name__,))
127+
raise NotImplementedError(
128+
"cannot instantiate %r on your system" % (cls.__name__,)
129+
)
110130
if cls is UniversalPath:
111131
self._init(*args, **kwargs)
112132
else:
@@ -118,77 +138,96 @@ def run_as_async(self, func, *args, **kwargs):
118138
def wrapper(*args, **kwargs):
119139
if isinstance(self.fs, AsyncFileSystem):
120140
result = None
141+
121142
async def async_runner():
122143
async def async_func():
123144
return await func(*args, **kwargs)
145+
124146
coro = async_func()
125147
done, pending = await asyncio.wait({coro})
126148
if coro is done:
127149
result = coro
150+
128151
asyncio.run(async_runner())
129152
return result
130153
else:
131154
return func(*args, **kwargs)
155+
132156
return wrapper
133-
134157

135-
class UniversalPath(UPath, PureUniversalPath):
136158

137-
__slots__ = ('_url', '_kwargs', '_closed', 'fs')
159+
class UniversalPath(UPath, PureUniversalPath):
138160

139-
not_implemented = ['cwd', 'home', 'expanduser', 'group', 'is_mount',
140-
'is_symlink', 'is_socket', 'is_fifo', 'is_block_device',
141-
'is_char_device', 'lchmod', 'lstat', 'owner', 'readlink']
161+
__slots__ = ("_url", "_kwargs", "_closed", "fs")
162+
163+
not_implemented = [
164+
"cwd",
165+
"home",
166+
"expanduser",
167+
"group",
168+
"is_mount",
169+
"is_symlink",
170+
"is_socket",
171+
"is_fifo",
172+
"is_block_device",
173+
"is_char_device",
174+
"lchmod",
175+
"lstat",
176+
"owner",
177+
"readlink",
178+
]
142179

143180
def _init(self, *args, template=None, **kwargs):
144181
self._closed = False
145182
if not kwargs:
146183
kwargs = dict(**self._kwargs)
147184
else:
148185
self._kwargs = dict(**kwargs)
149-
self._url = kwargs.pop('_url') if kwargs.get('_url') else None
186+
self._url = kwargs.pop("_url") if kwargs.get("_url") else None
150187

151188
if not self._root:
152189
if not self._parts:
153-
self._root = '/'
154-
elif self._parts[0] == '/':
190+
self._root = "/"
191+
elif self._parts[0] == "/":
155192
self._root = self._parts.pop(0)
156-
if getattr(self, '_str', None):
157-
delattr(self, '_str')
193+
if getattr(self, "_str", None):
194+
delattr(self, "_str")
158195
if template is not None:
159196
self._accessor = template._accessor
160197
else:
161198
self._accessor = _FSSpecAccessor(self._url, *args, **kwargs)
162199
self.fs = self._accessor._fs
163200

164201
def __getattribute__(self, item):
165-
if item == '__class__':
202+
if item == "__class__":
166203
return UniversalPath
167-
if item in getattr(UniversalPath, 'not_implemented'):
168-
raise NotImplementedError(f'UniversalPath has no attribute {item}')
204+
if item in getattr(UniversalPath, "not_implemented"):
205+
raise NotImplementedError(f"UniversalPath has no attribute {item}")
169206
else:
170-
return super().__getattribute__(item)
207+
return super().__getattribute__(item)
171208

172209
def _format_parsed_parts(self, drv, root, parts):
173-
join_parts = parts[1:] if parts[0] == '/' else parts
174-
if (drv or root):
210+
join_parts = parts[1:] if parts[0] == "/" else parts
211+
if drv or root:
175212
path = drv + root + self._flavour.join(join_parts)
176213
else:
177214
path = self._flavour.join(join_parts)
178215
scheme, netloc = self._url.scheme, self._url.netloc
179-
scheme = scheme + ':'
180-
netloc = '//' + netloc if netloc else ''
216+
scheme = scheme + ":"
217+
netloc = "//" + netloc if netloc else ""
181218
formatted = scheme + netloc + path
182219
return formatted
183220

184221
@property
185222
def path(self):
186223
if self._parts:
187-
join_parts = self._parts[1:] if self._parts[0] == '/' else self._parts
224+
join_parts = (
225+
self._parts[1:] if self._parts[0] == "/" else self._parts
226+
)
188227
path = self._flavour.join(join_parts)
189228
return self._root + path
190229
else:
191-
return '/'
230+
return "/"
192231

193232
def open(self, *args, **kwargs):
194233
return self._accessor.open(self, *args, **kwargs)
@@ -202,13 +241,13 @@ def iterdir(self):
202241
for name in self._accessor.listdir(self):
203242
# fsspec returns dictionaries
204243
if isinstance(name, dict):
205-
name = name.get('name')
206-
if name in {'.', '..'}:
244+
name = name.get("name")
245+
if name in {".", ".."}:
207246
# Yielding a path object for these makes little sense
208247
continue
209248
# only want the path name with iterdir
210249
sp = self.path
211-
name = re.sub(f'^({sp}|{sp[1:]})/', '', name)
250+
name = re.sub(f"^({sp}|{sp[1:]})/", "", name)
212251
yield self._make_child_relpath(name)
213252
if self._closed:
214253
self._raise_closed()
@@ -217,33 +256,32 @@ def exists(self):
217256
"""
218257
Whether this path exists.
219258
"""
220-
if not getattr(self._accessor, 'exists'):
259+
if not getattr(self._accessor, "exists"):
221260
try:
222261
self._accessor.stat(self)
223262
except (FileNotFoundError):
224263
return False
225264
return True
226265
else:
227266
return self._accessor.exists(self)
228-
229267

230268
def is_dir(self):
231269
info = self._accessor.info(self)
232-
if info['type'] == 'directory':
270+
if info["type"] == "directory":
233271
return True
234272
return False
235273

236274
def is_file(self):
237275
info = self._accessor.info(self)
238-
if info['type'] == 'file':
276+
if info["type"] == "file":
239277
return True
240278
return False
241279

242280
def glob(self, pattern):
243281
path = self.joinpath(pattern)
244282
for name in self._accessor.glob(self, path=path.path):
245283
sp = self.path
246-
name = re.sub(f'^({sp}|{sp[1:]})/', '', name)
284+
name = re.sub(f"^({sp}|{sp[1:]})/", "", name)
247285
name = name.split(self._flavour.sep)
248286
yield self._make_child(self._parts + name)
249287

@@ -268,9 +306,9 @@ def unlink(self, missing_ok=False):
268306
# asyncio.run(async_unlink())
269307

270308
def rmdir(self, recursive=True):
271-
'''Add warning if directory not empty
309+
"""Add warning if directory not empty
272310
assert is_dir?
273-
'''
311+
"""
274312
try:
275313
assert self.is_dir()
276314
except:
@@ -301,4 +339,3 @@ def _from_parsed_parts(self, drv, root, parts, init=True):
301339
if init:
302340
obj._init(**self._kwargs)
303341
return obj
304-

0 commit comments

Comments
 (0)