Python 获取函数或类中引用的所有类类型
我正在开发一个代码分析器,并试图识别Python中函数或类中引用的所有类类型 例如,假设我有这门课:Python 获取函数或类中引用的所有类类型,python,python-3.x,introspection,Python,Python 3.x,Introspection,我正在开发一个代码分析器,并试图识别Python中函数或类中引用的所有类类型 例如,假设我有这门课: import collections Bar = collections.namedtuple('Bar', ['bar']) Baz = collections.namedtuple('Baz', ['baz']) class Foo(object): def get_bar(self): return Bar(1) def get_baz(self):
import collections
Bar = collections.namedtuple('Bar', ['bar'])
Baz = collections.namedtuple('Baz', ['baz'])
class Foo(object):
def get_bar(self):
return Bar(1)
def get_baz(self):
return Baz(2)
我正在寻找一种可以获得函数和类类型的方法。大概是这样的:
print(get_types(Foo.get_bar)) # ['Bar']
print(get_types(Foo.get_baz)) # ['Baz']
print(get_types(Foo)) # ['Bar','Baz']
一种解决方案可能涉及使用类型注释。将
get_bar()
的返回值设置为bar
,将get_baz()
的返回值设置为baz
,您可以编写get_types()
,如下所示
import inspect
import collections
Bar = collections.namedtuple('Bar', ['bar'])
Baz = collections.namedtuple('Baz', ['baz'])
class Foo(object):
def get_bar(self) -> Bar:
return Bar(1)
def get_baz(self) -> Baz:
return Baz(2)
def get_types(obj):
if inspect.isclass(obj):
methods = [method for method in dir(obj)
if callable(getattr(obj, method)) and not method.startswith('_')]
return [get_types(getattr(obj, method)) for method in methods]
if callable(obj):
return [obj.__annotations__['return'].__name__]
def main():
print(get_types(Foo.get_bar)) # ['Bar']
print(get_types(Foo.get_baz)) # ['Baz']
print(get_types(Foo)) # ['Bar','Baz']
if __name__ == '__main__':
main()
在
get\u types(obj)
中,如果obj
包含类的实例,则可以选择该类的非私有方法,并在每个方法上返回get\u types()
。如果obj
包含一个函数,那么我们只返回该函数的return
属性。有趣的是,我怀疑其中有一种方法可以帮助实现这一点,看起来它可能有助于解决您的问题。您是否在寻找类型注释?请注意,返回条(1)
是否返回一个条
、某个其他类型、随机类型或带异常的爆炸不能仅从该源代码中得知。您愿意对您的代码做哪些假设?@MisterMiyagi类型的注释可以工作,但需要我们通过大量没有注释的旧代码重新添加注释。这是一条潜在的解决途径。我真正想要的是每个函数中的所有ORM类型(我们正在使用Peewee),这样我们就可以确定哪些函数与哪些DB表相接触。函数的执行对此并不重要,只要源代码在其逻辑的任何分支中包含类型即可。正在分析的一些代码具有我们在mypy中使用的类型注释,但有许多遗留代码没有。这似乎很有希望,但需要我们回顾所有代码并填写所有注释。