How to get a unique function name for methods

Terry Reedy tjreedy at udel.edu
Fri Oct 30 01:30:53 CET 2009


Philip Guo wrote:
> Hi all,
> 
> This is my first post, so sorry for the n00bish question.  Let's say I 
> have 2 classes with the same __init__ method defined in a file foo.py:
> 
> class A:
>   def __init__(self):
>     pass
> 
> class B:
>   def __init__(self):
>     pass
> 
> For the purpose of a code analysis, I need to get a UNIQUE name for each 
> of the two __init__ methods.  In the Python code object, i can get 
> co_name and co_filename, which returns me the method name and filename, 
> respectively, but NOT the enclosing classname.  This is a problem since 
> both A.__init__ and B.__init__ will show up as {co_name: "__init__", 
> co_filename: "foo.py"} in my analysis.  Ideally, I want to distinguish 
> them by their class names:
> 
> {co_name: "__init__", co_filename: "foo.py", classname: "A"}
> {co_name: "__init__", co_filename: "foo.py", classname: "B"}
> 
> (Simply using their line numbers isn't gonna work for me, I need their 
> class names.)
> 
> Does anyone know how to get this information either from a code object 
> or from a related object?  I am hacking the interpreter, so I have full 
> access to everything.

I do not quite understand your question. 1) a method is simply a 
function accessed as a class attribute. Like all attributes, methods do 
not really belong to any particular class, even if they look like they 
do. 2) if you access a function as a class attribute, as I presume you 
did, then you already know the class.

If you are asking "How to I recover class info after discarding it?", 
then the answer is "You can't, don' discard the info!".

Terry Jan Reedy




More information about the Python-list mailing list