Mar-30-2023, 06:51 PM
Hello,
I'm trying to create a object which can use the names provided by python-dot-syntax.
I would use these names as a path to lookup for data in another data structure, which would then check if the provided path exist or not.
I've tried implementing this using
This is the prototype I've been working:
I've wondered if I can live inspect the stack trace to determine that, but that's a long shot.
There are some other approaches to achieve this lookup while still using dot notation, like making a lookup to the data structure on each access, but this solution would make a more clean and decoupled design than the alternatives I've considered.
Any help is appreciated,
Thanks!
I'm trying to create a object which can use the names provided by python-dot-syntax.
I would use these names as a path to lookup for data in another data structure, which would then check if the provided path exist or not.
s = Shell() print(s.this.is.a.path) # [out]: "appropriate_paths_value" if found value for `this.is.path` in the data structure OR # [out]: None if not foundIt is worth noticing that
Shell
in this example does not hold the data. It should just get the path `"this.is.a.path" and ask the data structure, which is another object, if it exists.I've tried implementing this using
__getattribute__
, but I can't know when a given line has finished evaluating, therefore I cannot separate names from different dot-chains.This is the prototype I've been working:
def main(): a = DotGetter() print(f"{a.foo.bar=}") # [out]: ["foo", "bar"] (ok) # [expected]: ["foo", "bar"] print(f"{a.spam=}") # [out]: ["foo", "bar", "spam"] (not ok) # [expected]: ["spam"] class DotGetter: """ d = DotGetter() d.foo.bar -> ["foo", "bar"] d.spam -> ["spam"] """ def __init__(self, path: list[str] | None = None): self._path = path if path else [] def __getattribute__(self, name): # special name handling if not name.startswith("_") and not name.startswith("__"): self_path = object.__getattribute__(self, "_path") self_path.append(name) return DotGetter(self_path) # normal name handling return object.__getattribute__(self, name) def __repr__(self): return str(self._path) if __name__ == "__main__": exit(main())I guess I need some kind of hook to be called when the __getattribute__ chain in the same line has finished, but I've no idea if this is even possible.
I've wondered if I can live inspect the stack trace to determine that, but that's a long shot.
There are some other approaches to achieve this lookup while still using dot notation, like making a lookup to the data structure on each access, but this solution would make a more clean and decoupled design than the alternatives I've considered.
Any help is appreciated,
Thanks!