2

背景:使用 numpy/scipy 从 R 迁移到 Python。尝试制作一些有用功能的小模块。特别是,我正在尝试创建一个递归元素类型检查器。

问题:是否可以在 Python 环境中获取正在调用函数的当前有效类型的列表?

例如,isinstance(1,int)将返回Trueisinstance(1,str)将返回False,但isinstance(1,asdf)将抛出一个NameError: name 'asdf' is not defined即 int 和 str 已定义,但 asdf 未定义。如何获取已定义的类型列表或当前 Python 环境中存在的名称,并按类型过滤它们?

4

2 回答 2

2

在 Python 中,类型本身就是普通对象。也就是说,例如,

type('hello') == str
type(5) == int
type(int) == type
type(type) == type

都是True

因此,要做到这一点,请在范围内查找指向 type 对象的所有变量type

要获取范围内的所有对象,请查看两者dir()(不包括内置名称,如int)和dir(__builtins__)(内置名称) locals()(在当前函数中定义的globals()变量)、(在当前模块中的函数之外定义的变量)和vars(__builtins__)(内置名称)。这些都是来自 name => object 的字典,因此将它们全部组合并获取对象:

objs = dict(vars(__builtins__), **dict(globals(), **locals())).values()

并仅过滤类型:

types_in_scope = [o for o in objs if isinstance(o, type)]

请注意,这些只是范围内指向类型的变量。很有可能引用一个类型未分配给范围内任何变量的对象。例如:

def foo():
    class Foo:
        pass
    return Foo()
x = foo()
于 2012-08-04T08:46:37.500 回答
0

也许您可以查找types模块?请在此处查看文档:http: //docs.python.org/library/types.html。您还可以获取程序中的当前变量,如下所示:

In [9]: def spam():
            x=5
            y=6

In [10]: spam.func_code.co_varnames
Out[10]: ('x', 'y')

希望它有所帮助,您可以开始使用。对不起,如果我完全偏离了轨道。

于 2012-08-04T07:13:57.353 回答