diff --git a/src/scippnexus/base.py b/src/scippnexus/base.py index 5b3185bc..1a635233 100644 --- a/src/scippnexus/base.py +++ b/src/scippnexus/base.py @@ -7,6 +7,7 @@ import warnings from collections.abc import Mapping from functools import lru_cache +from pathlib import PurePosixPath from types import MappingProxyType from typing import Any, Dict, Iterator, List, Optional, Tuple, Union, overload @@ -380,13 +381,15 @@ def __getitem__(self, sel): # create the parent group, to ensure that fields get the correct properties # such as sizes and dtype. if '/' in sel: - if sel.startswith('/'): - return self.file[sel[1:]] - elif sel.endswith('/'): - return self[sel[:-1]] + sel_path = PurePosixPath(sel) + if sel_path.is_absolute(): + return self.file[sel_path.relative_to('/').as_posix()] + # If the path is a single name, we can directly access the child + elif len(sel_path.parts) == 1: + return self[sel_path.as_posix()] else: - grp, path = sel.split('/', 1) - return self[grp][path] + grp = sel_path.parts[0] + return self[grp][sel_path.relative_to(grp).as_posix()] child = self._children[sel] if isinstance(child, Field): self._populate_fields() diff --git a/tests/nexus_test.py b/tests/nexus_test.py index f87e5ae9..96aecafa 100644 --- a/tests/nexus_test.py +++ b/tests/nexus_test.py @@ -678,3 +678,9 @@ def test_empty_class_does_not_warn(nxroot, nxclass): def test_trailing_forward_slash_in_path_does_not_change_file_object(nxroot): assert id(nxroot['entry/']) == id(nxroot['entry']) + + +def test_path_santization(nxroot): + nxroot['entry'].create_class('log', NXlog) + assert id(nxroot['/entry/log']) == id(nxroot['/entry//log']) + assert id(nxroot['entry/log']) == id(nxroot['entry//log'])