[Python-ideas] Get the class that *defines* a method

anatoly techtonik techtonik at gmail.com
Sun Jun 23 21:42:51 CEST 2013


Currently, the only way to get the name of the class that *defines* a
method is to get chain of parent classes from inspect.getmro() and look
into every class's dict until a given name is found. Knowing that dict
contains not only methods, and knowing that it can be modified at run-time,
this doesn't seem too reliable for me (unless Python itself does the same).


At first I wanted to propose an enhancement to runtime skeleton of Python,
which is 2D lookup tree for objects and containers that define them. But
then I realized that it will may not reflect the model I need. For example,
classes need to provide their parent classes, but in my model classes need
to provide module name (or function name, or method name) in which they are
defined.

And while writing this I realized that *definition* scope may be different
from *run-time* scope, and Python doesn't make it clear:

>>> def lll():
...   class A(object):
...     pass
...   a=A()
...   return a
...
>>> lll()
<__main__.A object at 0x948252c>
>>> __main__.A
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name '__main__' is not defined

The A object is said to be in __main__ namespace, but it seems to be a
run-time namespace local to function and it seems like Python loses this
information. There is no information about the function that defined the
class (owner, parent or .?.), and hence no info about container of the
function, which makes it hard to assume the scope of variables for this
class at run-time.


So, the above is a generalization of a simple idea - store the "structure
reference" of the class that *defines* a method inside this method.
"structure reference" here is the address in the nested scopes formed by
Python definitions.

The specific action items for you here are:
1. is that stuff will be useful (for me it brings some much needed
consistency into the chaos of run-time Python object space)
2. what is the best way to define/cache the reference to the class defining
the method?
3. what is the best way to define/cache the reference to the scope defining
the method?
4. what is the best way to organize storing of this static scope structure
information at run-time?

See method.im_class note at
http://docs.python.org/2/library/inspect.html#types-and-members

"Namespaces are one honking great idea -- let's do more of those!" (c)
import this
-- 
anatoly t.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20130623/9ef99461/attachment.html>


More information about the Python-ideas mailing list