Repository navigation
Conversation
Deleting an object with a path, such as del f["d/h"], was a silent no-op: _get_del_search walked the path and returned the selected object without deleting anything. The last path component is now deleted from its parent directory, so paths, cycles (d/h;1), leading and doubled slashes and whole directories (d/) all work; a path that selects nothing still raises KeyInFileError and deletes nothing. WritableDirectory.__contains__ also agrees with item lookup for cycles and paths now, so "h;2" in f and "d/h" in f match what f[...] can read. Fixes scikit-hep#1807
ariostas
left a comment
There was a problem hiding this comment.
🤖 AI text below 🤖
Thanks for the fix! Deleting by path works as described. I left two inline comments: one on __contains__ loading objects during membership checks, and one on del f["/"] still doing nothing silently. Both include reproducers.
| if isinstance(where, str) and (";" in where or "/" in where): | ||
| try: | ||
| self._get_del_search(where, True) | ||
| except uproot.KeyInFileError: | ||
| pass | ||
| else: | ||
| return True |
There was a problem hiding this comment.
🤖 AI text below 🤖
"d/t" in f now loads and builds the object it is checking for, because it goes through _get_del_search(where, True) and then _get. Only KeyInFileError is caught, so other errors from loading leak out of in.
On an uproot.update() of a file-like object, it raises instead of returning True, even though "t" in f["d"] works:
import numpy as np
import uproot
with uproot.recreate("m.root") as f:
f.mktree("d/t", {"x": np.int64})
f["d/t"].extend({"x": np.arange(3)})
class FileLike: # any object that isn't a path
def __init__(self, f): self.f = f
def __getattr__(self, k): return getattr(self.f, k)
with open("m.root", "r+b") as fo, uproot.update(FileLike(fo)) as f:
print("t" in f["d"]) # True
print("d/t" in f) # TypeError: uproot.update() on a file-like object does not support accessing existing TTreesOn main this returned False: wrong, but no crash. The same happens for RNTuples.
With an ordinary file path the answer is right, but checking membership has side effects. A writable tree or RNTuple is built and registered in f._file._trees or f._file._ntuples, and "h;2" in f reads and decompresses the whole histogram:
with uproot.update("m.root") as f:
print(len(f._file._trees)) # 0
"d/t" in f
print(len(f._file._trees)) # 1Could this check that the key exists instead of reading it? For example (untested sketch):
items = [item for item in where.split("/") if item != ""]
step = self
for item in items[:-1]:
key = step._cascading.data.get_key(*_parse_name_cycle(item))
if key is None or key.classname.string not in ("TDirectory", "TDirectoryFile"):
return False
step = step._subdir(key)
return bool(items) and step._cascading.data.get_key(*_parse_name_cycle(items[-1])) is not NoneThis would also make "/" in f return False (it is True now), which matches keys().
There was a problem hiding this comment.
Updated WritableDirectory.__contains__ in c2080b7ab590be6be5c0091daae55d358e80da84 to traverse subdirectories and inspect DirectoryData.get_key(*_parse_name_cycle(...)) without calling step[item] or loading objects.
- Checking
"d/t"no longer populatesf._file._treesand works onuproot.update(file_object). - Trailing-slash, empty-path (
"/","//"), and non-directory intermediate ("h/x") checks now returnFalse. ruff check src/uproot/writing/writable.py,black --check, andpytest tests/test_1807_delete_by_path.py tests/test_1833_cov_writing_writable.py tests/test_1778_delete_older_cycle.pypass locally (64 passed, 8 skipped for optionalROOT/pandas, with full line+branch coverage on the modified lines).
| last_item = max( | ||
| (i for i, item in enumerate(items) if item != ""), default=None | ||
| ) |
There was a problem hiding this comment.
🤖 AI text below 🤖
If the path has no non-empty parts, last_item is None, so nothing is deleted and step (the directory itself) is returned. That is the same silent no-op this PR fixes for other paths:
with uproot.update("m.root") as f:
del f["/"] # no error ("//" does the same)
print(f.keys()) # ['d;1', 'd/t;1']: nothing deletedmain behaves the same way, so this isn't a regression, but it would be good to cover here. For example, raise KeyInFileError (or ValueError) when not isget and last_item is None.
There was a problem hiding this comment.
Updated WritableDirectory._get_del_search in c2080b7ab590be6be5c0091daae55d358e80da84 to raise uproot.KeyInFileError when last_item is None and not isget (so del f["/"] and del f["//"] raise instead of returning self, while f["/"] still returns self). Added regression tests in tests/test_1807_delete_by_path.py.
del f["d/h"]was a silent no-op.WritableDirectory._get_del_searchsplit anypath on
/, walked it and returned the selected object without ever calling_del, so nothing was deleted and no error was raised. This affected histogramsand trees alike, with or without a cycle number.
What changed:
d/h,d/h;1,/d/h,d/h/,d//handd/(a whole directory) all deletewhat they select. Paths that select nothing (
d/nothere,d/h;9,d/t/x,d/t:x) still raiseKeyInFileErrorand delete nothing.WritableDirectory.__contains__now agrees with item lookup for cycles andpaths, so
"h;2" in fand"d/h" in fareTrue, as they already were forread-only files. Recursive lookup of a bare name (
"h" in fwhen the key livesin a subdirectory) is unchanged.
_parse_name_cycle.Testing
tests/test_1807_delete_by_path.py(new, 14 tests) covers deletion by path andcycle, leading/trailing/doubled slashes, whole directories, trees, the
"selects nothing" errors, and
inwith cycles and paths.python -m pytest tests/test_1807_delete_by_path.py -q: 14 passed with the fix.With
src/uproot/writing/writable.pyreverted, the same command gives 9 failed,5 passed.
python -m pytest tests -q -m "not network and not slow and not distributed and not xrootd" -n 8:4615 passed, 231 skipped, 2 failed. The two failures are
test_1767_graphed_write_duplicate_paths.py::test_workers_read_the_path_as_given,which fail on this Windows machine with or without the change because creating a
symlink needs a privilege the machine does not have (
WinError 1314).black --checkandruff checkon both changed files: clean.writable.pyare covered by the new tests.Fixes #1807
AI disclosure: this change was written with AI assistance (DeepSeek V4.1 Flash).