[Python-ideas] Add __parent__ to all classes, functions, and modules
Neil Girdhar
mistersheik at gmail.com
Sun Oct 5 19:27:16 CEST 2014
Many classes, functions, and modules are defined within the context of
another class, function, or module thereby forming a mathematical forest of
declarations. It is possible to walk the descendants using __dict__ (for
classes and modules), but not the ancestors. I propose adding __parent__
that would be filled at the same time that __qualname__ is filled in. One
concrete use case for __parent__ is allowing a method decorator to call
super, which is currently impossible because the class in which the method
has been defined is not available to the decorator. This way, one could
write:
def ensure_finished(iterator):
try:
next(iterator)
except StopIteration:
return
else:
raise RuntimeError
def derived_generator(method):
def new_method(self, *args, **kwargs):
x = method(self, *args, **kwargs)
y = getattr(super(method.__parent__, self), method.__name__)\
(*args, **kwargs)
for a, b in zip(x, y):
assert a is None and b is None
yield
ensure_finished(x)
ensure_finished(y)
This is currently impossible to implement without restating the class name
every time the decorator is used as far as I know.
Best,
Neil
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20141005/438084c5/attachment.html>
More information about the Python-ideas
mailing list