开发者

Python How to list all methods/classes that have been imported into a class

How to list all methods/classes that have been imported into a class. Take an example

from module1 import method1
from module2 import method2

class foo(object):
   def say_foo(self):
      method1()
   def talk(self):
      method2()

is it possible to list all methods used in the foo class? i know inspect.get开发者_JS百科members(foo) will list talk and say_foo, how do i list method1 and method2?


To be brutally honest, your question doesn't make a whole lot of sense, and here is why:

At the point when foo is defined, no connection is made between the two globals called by say_foo and talk and the two functions imported at the top of your code.

For example, the interpreter will not complain about the following:

class foo(object):
   def say_foo(self):
      method1()
   def talk(self):
      method2()

Despite the absence of imports, this is still valid code. You won't of course be able to call say_foo and talk without getting a NameError.

The following is also fine:

from module1 import method1
from module2 import method2

class foo(object):
   def say_foo(self):
      method1()
   def talk(self):
      method2()

obj1 = foo()
obj1.say_foo()

def method1(): pass

obj1.say_foo()
obj2 = foo()
obj2.say_foo()

I leave to you to figure out which method1 gets invoked when.

Now, having said all that, there is something you can do. If you examine the method object's co_names, that'll give you the list of names that are used by the method:

In [30]: foo.say_foo.im_func.func_code.co_names
Out[30]: ('method1',)

In [31]: foo.talk.im_func.func_code.co_names
Out[31]: ('method2',)

This clearly isn't exactly the same as what you're asking, and may or may not be useful depending on what you intend to do with this.

It is also almost certainly CPython-specific.


use ast module to analyze you code:

code = """
from module1 import method1
from module2 import method2

class foo(object):
   def say_foo(self):
      method1()
   def talk(self):
      method2()
"""

import ast, _ast

t = ast.parse(code)
for node in ast.walk(t):
    if isinstance(node, ast.ClassDef) and node.name == "foo":
        klass = node
        break

for node in ast.walk(klass):
    if isinstance(node, _ast.Call):
        print node.func.id

the output is :

method1
method2


What? method1 and method2 haven't been "imported into" the foo class. They're imported in the module, so dir(foomodule) will show them. But there's simply no reference from foo to method1.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜