can any recursive looping happen from overwriting __dir__ in python -
suppose, have custom class not inherit class (which typically hard inherit from), builds wrapper along few other functions modify behavior of second class.
class testclass: def __init__(self, *args, **kwargs): self.data = origclass(*args, **kwargs) def __getitem__(self, key): ... x = self.data.__getitem__(key) ... def __setitem__(self, key, value): ... self.data.__setitem__(key, value) ... @staticmethod def _try_attr(var, item): if hasattr(var, item): return var.__getattribute__(item) else: return none def __getattr__(self, item): return testclass._try_attr(self._data, item) def __repr__(self): ... def __str__(self): ...
as such, testclass
working fine new modifications, , falling on origclass
methods using __getattr__
methods not re-implemented. however, in interactive mode (e.g. pycharm's python console) or otherwise, when try see __dir__()
, __dir__()
in testclass
doesn't display / show attributes in origclass
accessible in testclass
.
i can try create new __dir__
function within testclass
merge current testclass
's __dir__
__dir__
in origclass
create __dir__
(i'm using python 3.x). there seems posts on over (although not sure of them valid python 3.x).
however, worried common functions in
origclass
,testclass
, i.e. if there functions__setitem__
,__getitem__
in bothorigclass
,testclass
, ones new__dir__
refer to?are there other functions (e.g.
__
functions such__getitem__
,__setattr__
etc.) refer__dir__
? or, in other words, chance of falling recursive loop if overwrite__dir__
?
__dir__
returns list of unique strings; it'll include strings'__setitem__'
,'__getitem__'
without reference specific implementation.in other words, doesn't matter if refer
testclass
ororigclass
implementation. accessing attribute name ontestclass
findtestclass
implementation.__dir__
purely informative , useddir()
command. other tools (such pythonhelp()
system) may rely ondir()
.you'll not recursive loop, method entirely optional, there no base implementation
dir()
otherwise collects information object other means.
you can use dir()
on self.data
attribute, , append resulting list create testclass
version:
def __dir__(self): base = dir(self.data) base.extend(('_try_attr', 'data')) return base
the resulting list of strings sorted again dir()
.
Comments
Post a Comment