Skip to content

Commit 1d1547b

Browse files
Apply Sourcery suggestions and fix typos
1 parent 01ecda4 commit 1d1547b

29 files changed

+94
-103
lines changed

docs/source/changelog.rst

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -103,7 +103,7 @@ Enhancements
103103
- "tree" text display of filesystem contents (#1750)
104104
- async wrapper for sync FSs (#1745)
105105
- new known implementation: tosfs (#1739)
106-
- consilidate block fetch requests (#1733)
106+
- consolidate block fetch requests (#1733)
107107

108108
Fixes
109109

fsspec/archive.py

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -43,8 +43,8 @@ def info(self, path, **kwargs):
4343
return {"name": "", "type": "directory", "size": 0}
4444
if path in self.dir_cache:
4545
return self.dir_cache[path]
46-
elif path + "/" in self.dir_cache:
47-
return self.dir_cache[path + "/"]
46+
elif f"{path}/" in self.dir_cache:
47+
return self.dir_cache[f"{path}/"]
4848
else:
4949
raise FileNotFoundError(path)
5050

@@ -69,7 +69,6 @@ def ls(self, path, detail=True, **kwargs):
6969
out = {"name": ppath, "size": 0, "type": "directory"}
7070
paths[ppath] = out
7171
if detail:
72-
out = sorted(paths.values(), key=operator.itemgetter("name"))
73-
return out
72+
return sorted(paths.values(), key=operator.itemgetter("name"))
7473
else:
7574
return sorted(paths)

fsspec/asyn.py

Lines changed: 10 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -85,10 +85,8 @@ def sync(loop, func, *args, timeout=None, **kwargs):
8585
result = [None]
8686
event = threading.Event()
8787
asyncio.run_coroutine_threadsafe(_runner(event, coro, result, timeout), loop)
88-
while True:
89-
# this loops allows thread to get interrupted
90-
if event.wait(1):
91-
break
88+
while not event.wait(1):
89+
# this loop allows thread to get interrupted
9290
if timeout is not None:
9391
timeout -= 1
9492
if timeout < 0:
@@ -356,10 +354,11 @@ async def _copy(
356354
batch_size=None,
357355
**kwargs,
358356
):
359-
if on_error is None and recursive:
360-
on_error = "ignore"
361-
elif on_error is None:
362-
on_error = "raise"
357+
if on_error is None:
358+
if recursive:
359+
on_error = "ignore"
360+
else:
361+
on_error = "raise"
363362

364363
if isinstance(path1, list) and isinstance(path2, list):
365364
# No need to expand paths when both source and destination
@@ -714,7 +713,7 @@ async def _walk(self, path, maxdepth=None, on_error="omit", **kwargs):
714713
detail = kwargs.pop("detail", False)
715714
try:
716715
listing = await self._ls(path, detail=True, **kwargs)
717-
except (FileNotFoundError, OSError) as e:
716+
except OSError as e:
718717
if on_error == "raise":
719718
raise
720719
elif callable(on_error):
@@ -766,7 +765,7 @@ async def _glob(self, path, maxdepth=None, **kwargs):
766765
ends_with_sep = path.endswith(seps) # _strip_protocol strips trailing slash
767766
path = self._strip_protocol(path)
768767
append_slash_to_dirname = ends_with_sep or path.endswith(
769-
tuple(sep + "**" for sep in seps)
768+
tuple(f"{sep}**" for sep in seps)
770769
)
771770
idx_star = path.find("*") if path.find("*") >= 0 else len(path)
772771
idx_qmark = path.find("?") if path.find("?") >= 0 else len(path)
@@ -814,7 +813,7 @@ async def _glob(self, path, maxdepth=None, **kwargs):
814813
p: info
815814
for p, info in sorted(allpaths.items())
816815
if pattern.match(
817-
p + "/"
816+
f"{p}/"
818817
if append_slash_to_dirname and info["type"] == "directory"
819818
else p
820819
)

fsspec/caching.py

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -430,8 +430,7 @@ def _fetch_block(self, block_number: int) -> bytes:
430430
self.total_requested_bytes += end - start
431431
self.miss_count += 1
432432
logger.info("BlockCache fetching block %d", block_number)
433-
block_contents = super()._fetch(start, end)
434-
return block_contents
433+
return super()._fetch(start, end)
435434

436435
def _read_cache(
437436
self, start: int, end: int, start_block_number: int, end_block_number: int
@@ -704,7 +703,7 @@ class UpdatableLRU(Generic[P, T]):
704703
"""
705704
Custom implementation of LRU cache that allows updating keys
706705
707-
Used by BackgroudBlockCache
706+
Used by BackgroundBlockCache
708707
"""
709708

710709
class CacheInfo(NamedTuple):
@@ -857,7 +856,7 @@ def _fetch(self, start: int | None, end: int | None) -> bytes:
857856
self._fetch_future = None
858857
else:
859858
# Must join if we need the block for the current fetch
860-
must_join = bool(
859+
must_join = (
861860
start_block_number
862861
<= self._fetch_future_block_number
863862
<= end_block_number
@@ -920,8 +919,7 @@ def _fetch_block(self, block_number: int, log_info: str = "sync") -> bytes:
920919
logger.info("BlockCache fetching block (%s) %d", log_info, block_number)
921920
self.total_requested_bytes += end - start
922921
self.miss_count += 1
923-
block_contents = super()._fetch(start, end)
924-
return block_contents
922+
return super()._fetch(start, end)
925923

926924
def _read_cache(
927925
self, start: int, end: int, start_block_number: int, end_block_number: int

fsspec/core.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -339,7 +339,7 @@ def _un_chain(path, kwargs):
339339
if "://" in p or x.match(p):
340340
bits.append(p)
341341
else:
342-
bits.append(p + "://")
342+
bits.append(f"{p}://")
343343
else:
344344
bits = [path]
345345
# [[url, protocol, kwargs], ...]

fsspec/fuse.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -76,8 +76,7 @@ def read(self, path, size, offset, fh):
7676

7777
f = self.cache[fh]
7878
f.seek(offset)
79-
out = f.read(size)
80-
return out
79+
return f.read(size)
8180

8281
def write(self, path, data, offset, fh):
8382
logger.debug("write %s", (path, offset))
@@ -119,7 +118,7 @@ def unlink(self, path):
119118
fn = "".join([self.root, path.lstrip("/")])
120119
try:
121120
self.fs.rm(fn, False)
122-
except (OSError, FileNotFoundError) as exc:
121+
except OSError as exc:
123122
raise FuseOSError(EIO) from exc
124123

125124
def release(self, path, fh):

fsspec/implementations/cache_metadata.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -166,7 +166,7 @@ def on_close_cached_file(self, f: Any, path: str) -> None:
166166
167167
The actual closing of the file is the responsibility of the caller.
168168
"""
169-
# File must be writeble, so in self.cached_files[-1]
169+
# File must be writeable, so in self.cached_files[-1]
170170
c = self.cached_files[-1][path]
171171
if c["blocks"] is not True and len(c["blocks"]) * f.blocksize >= f.size:
172172
c["blocks"] = True

fsspec/implementations/cached.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -338,7 +338,7 @@ def _open(
338338
# explicitly submitting the size to the open call will avoid extra
339339
# operations when opening. This is particularly relevant
340340
# for any file that is read over a network, e.g. S3.
341-
size = detail.get("size", None)
341+
size = detail.get("size")
342342

343343
# call target filesystems open
344344
self._mkcache()
@@ -821,7 +821,7 @@ def info(self, path, **kwargs):
821821
if f:
822822
size = os.path.getsize(f[0].fn) if f[0].closed else f[0].tell()
823823
return {"name": path, "size": size, "type": "file"}
824-
f = any(_.path.startswith(path + "/") for _ in self.transaction.files)
824+
f = any(_.path.startswith(f"{path}/") for _ in self.transaction.files)
825825
if f:
826826
return {"name": path, "size": 0, "type": "directory"}
827827
return self.fs.info(path, **kwargs)

fsspec/implementations/github.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -153,7 +153,7 @@ def ls(self, path, detail=False, sha=None, _sha=None, **kwargs):
153153
_sha = sha or self.root
154154
for part in parts:
155155
out = self.ls(so_far, True, sha=sha, _sha=_sha)
156-
so_far += "/" + part if so_far else part
156+
so_far += f"/{part}" if so_far else part
157157
out = [o for o in out if o["name"] == so_far]
158158
if not out:
159159
raise FileNotFoundError(path)

fsspec/implementations/http.py

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -446,7 +446,7 @@ async def _glob(self, path, maxdepth=None, **kwargs):
446446
"""
447447
Find files by glob-matching.
448448
449-
This implementation is idntical to the one in AbstractFileSystem,
449+
This implementation is identical to the one in AbstractFileSystem,
450450
but "?" is not considered as a character for globbing, because it is
451451
so common in URLs, often identifying the "query" part.
452452
"""
@@ -614,9 +614,11 @@ def read(self, length=-1):
614614
read only part of the data will raise a ValueError.
615615
"""
616616
if (
617-
(length < 0 and self.loc == 0) # explicit read all
617+
# explicit read all
618+
length < 0
619+
and self.loc == 0
618620
# but not when the size is known and fits into a block anyways
619-
and not (self.size is not None and self.size <= self.blocksize)
621+
and (self.size is None or self.size > self.blocksize)
620622
):
621623
self._fetch_all()
622624
if self.size is None:

fsspec/implementations/http_sync.py

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111

1212
try:
1313
import yarl
14-
except (ImportError, ModuleNotFoundError, OSError):
14+
except (ImportError, OSError):
1515
yarl = False
1616

1717
from fsspec.callbacks import _DEFAULT_CALLBACK
@@ -278,10 +278,9 @@ def encode_url(self, url):
278278
@classmethod
279279
def _strip_protocol(cls, path: str) -> str:
280280
"""For HTTP, we always want to keep the full URL"""
281-
path = path.replace("sync-http://", "http://").replace(
281+
return path.replace("sync-http://", "http://").replace(
282282
"sync-https://", "https://"
283283
)
284-
return path
285284

286285
@classmethod
287286
def _parent(cls, path):
@@ -310,7 +309,7 @@ def _ls_real(self, url, detail=True, **kwargs):
310309
l = l[1]
311310
if l.startswith("/") and len(l) > 1:
312311
# absolute URL on this server
313-
l = parts.scheme + "://" + parts.netloc + l
312+
l = f"{parts.scheme}://{parts.netloc}{l}"
314313
if l.startswith("http"):
315314
if self.same_schema and l.startswith(url.rstrip("/") + "/"):
316315
out.add(l)
@@ -715,9 +714,11 @@ def read(self, length=-1):
715714
read only part of the data will raise a ValueError.
716715
"""
717716
if (
718-
(length < 0 and self.loc == 0) # explicit read all
717+
# explicit read all
718+
length < 0
719+
and self.loc == 0
719720
# but not when the size is known and fits into a block anyways
720-
and not (self.size is not None and self.size <= self.blocksize)
721+
and (self.size is None or self.size > self.blocksize)
721722
):
722723
self._fetch_all()
723724
if self.size is None:

fsspec/implementations/local.py

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -235,10 +235,9 @@ def _parent(cls, path):
235235
else:
236236
# NT
237237
path_ = path.rsplit("/", 1)[0]
238-
if len(path_) <= 3:
239-
if path_[1:2] == ":":
240-
# nt root (something like c:/)
241-
return path_[0] + ":/"
238+
if len(path_) <= 3 and path_[1:2] == ":":
239+
# nt root (something like c:/)
240+
return path_[0] + ":/"
242241
# More cases may be required here
243242
return path_
244243

@@ -322,7 +321,7 @@ def make_path_posix(path):
322321
# windows full path like "C:\\local\\path"
323322
if len(path) <= 3:
324323
# nt root (something like c:/)
325-
return path[0] + ":/"
324+
return f"{path[0]}:/"
326325
path = path.replace("\\", "/")
327326
return path
328327
elif path[0:1] == "~":

fsspec/implementations/memory.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,7 @@ def _strip_protocol(cls, path):
3939
if "::" in path or "://" in path:
4040
return path.rstrip("/")
4141
path = path.lstrip("/").rstrip("/")
42-
return "/" + path if path else ""
42+
return f"/{path}" if path else ""
4343

4444
def ls(self, path, detail=True, **kwargs):
4545
path = self._strip_protocol(path)
@@ -56,7 +56,7 @@ def ls(self, path, detail=True, **kwargs):
5656
}
5757
]
5858
paths = set()
59-
starter = path + "/"
59+
starter = f"{path}/"
6060
out = []
6161
for p2 in tuple(self.store):
6262
if p2.startswith(starter):
@@ -151,7 +151,7 @@ def info(self, path, **kwargs):
151151
logger.debug("info: %s", path)
152152
path = self._strip_protocol(path)
153153
if path in self.pseudo_dirs or any(
154-
p.startswith(path + "/") for p in list(self.store) + self.pseudo_dirs
154+
p.startswith(f"{path}/") for p in list(self.store) + self.pseudo_dirs
155155
):
156156
return {
157157
"name": path,

fsspec/implementations/smb.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -172,7 +172,7 @@ def _connect(self):
172172
# will be equal to `wait`. For any number of retries the last wait time will be
173173
# equal to `wait` and for retries>2 the first wait time will be equal to `wait / factor`.
174174
wait_times = iter(
175-
factor ** (n / n_waits - 1) * wait_time for n in range(0, n_waits + 1)
175+
factor ** (n / n_waits - 1) * wait_time for n in range(n_waits + 1)
176176
)
177177

178178
for attempt in range(self.register_session_retries + 1):

fsspec/implementations/tests/conftest.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -27,13 +27,12 @@ def fs(request):
2727
pyarrow_fs = pytest.importorskip("pyarrow.fs")
2828
FileSystem = pyarrow_fs.FileSystem
2929
if request.param == "arrow":
30-
fs = ArrowFSWrapper(FileSystem.from_uri("file:///")[0])
31-
return fs
30+
return ArrowFSWrapper(FileSystem.from_uri("file:///")[0])
3231
cls = FILESYSTEMS[request.param]
3332
return cls()
3433

3534

3635
@pytest.fixture(scope="function")
3736
def temp_file():
3837
with tempfile.TemporaryDirectory() as temp_dir:
39-
return temp_dir + "test-file"
38+
return f"{temp_dir}test-file"

fsspec/implementations/tests/test_archive.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -191,7 +191,7 @@ def pytest_generate_tests(metafunc):
191191
scenario: ArchiveTestScenario = scenario
192192
label = scenario.protocol
193193
if scenario.variant:
194-
label += "-" + scenario.variant
194+
label = f"{label}-{scenario.variant}"
195195
idlist.append(label)
196196
argvalues.append([scenario])
197197
metafunc.parametrize(argnames, argvalues, ids=idlist, scope="class")

fsspec/implementations/tests/test_dbfs.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
itself changes, which is very unlikely to occur as it is versioned),
1010
you need to re-record the answers. This can be done as follows:
1111
12-
1. Delete all casettes files in the "./cassettes/test_dbfs" folder
12+
1. Delete all cassettes files in the "./cassettes/test_dbfs" folder
1313
2. Spin up a databricks cluster. For example,
1414
you can use an Azure Databricks instance for this.
1515
3. Take note of the instance details (the instance URL. For example for an Azure

fsspec/implementations/tests/test_github.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@ def test_github_cat():
4242

4343

4444
def test_github_ls():
45-
# test using ls to list the files in a resository
45+
# test using ls to list the files in a repository
4646
fs = fsspec.filesystem("github", org="mwaskom", repo="seaborn-data")
4747
ls_result = set(fs.ls(""))
4848
expected = {"brain_networks.csv", "mpg.csv", "penguins.csv", "README.md", "raw"}

fsspec/implementations/tests/test_memory.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -172,7 +172,7 @@ def test_moves(m):
172172
assert m.find("") == ["/target.txt", "/target2.txt"]
173173

174174

175-
def test_rm_reursive_empty_subdir(m):
175+
def test_rm_recursive_empty_subdir(m):
176176
# https://github.com/fsspec/filesystem_spec/issues/500
177177
m.mkdir("recdir")
178178
m.mkdir("recdir/subdir2")
@@ -211,7 +211,7 @@ def test_cp_directory_recursive(m):
211211
# https://github.com/fsspec/filesystem_spec/issues/1062
212212
# Recursive cp/get/put of source directory into non-existent target directory.
213213
src = "/src"
214-
src_file = src + "/file"
214+
src_file = f"{src}/file"
215215
m.mkdir(src)
216216
m.touch(src_file)
217217

fsspec/implementations/zip.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -161,9 +161,8 @@ def _matching_starts(file_path):
161161
continue
162162

163163
if file_info["type"] == "directory":
164-
if withdirs:
165-
if file_path not in result:
166-
result[file_path.strip("/")] = file_info
164+
if withdirs and file_path not in result:
165+
result[file_path.strip("/")] = file_info
167166
continue
168167

169168
if file_path not in result:

fsspec/mapping.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -60,8 +60,8 @@ def __init__(self, root, fs, check=False, create=False, missing_exceptions=None)
6060
f"Path {root} does not exist. Create "
6161
f" with the ``create=True`` keyword"
6262
)
63-
self.fs.touch(root + "/a")
64-
self.fs.rm(root + "/a")
63+
self.fs.touch(f"{root}/a")
64+
self.fs.rm(f"{root}/a")
6565

6666
@cached_property
6767
def dirfs(self):

0 commit comments

Comments
 (0)