简体   繁体   English

如何将字符串转换为变量名?

[英]How to convert string to variable name?

I would like to know how to convert a string input into a variable name to use into Python code.我想知道如何将字符串输入转换为变量名以用于 Python 代码。 A concrete example:一个具体的例子:

def insrospect(foo, bar):
    requested_module = makestringvariable(foo)
    requested_object = makestringvariable(bar)
    import requested_module
    for item in inspect.getmemebers(requested_module.requested_object):
        member = makestringvariable(item[0])
        if callable(requested_object.member):
           print item

if __name__ == '__main__':
    introspect(somemodule, someobject)

So here above, because i do not know which module to introspect before launching, i need to convert the string to a usable module name and because getmembers() returns the members as strings, i also need them to be converted into usable variable names to check if they are callable.所以在上面,因为我不知道在启动之前要自省哪个模块,我需要将字符串转换为可用的模块名称,并且因为getmembers()将成员作为字符串返回,我还需要将它们转换为可用的变量名称检查它们是否可调用。

Is there such a makestringvariable() function?有没有这样的makestringvariable() function?

with the __import__ function and the getattr magic, you will be able to directly write this:使用__import__ function 和getattr魔法,您将能够直接编写:

import importlib
def introspect(foo, bar):
    imported_module = importlib.import_module(foo)
    imported_object = getattr(imported_module, bar)
    for item in inspect.getmembers(imported_object):
        if callable(getattr(imported_object, item[0]):
           print item

if __name__ == '__main__':
    introspect(somemodule, someobject)

You can't convert a string into a variable as such, because variables are part of your code , not of your data .您不能将字符串转换为变量,因为变量是代码的一部分,而不是数据的一部分。 Usually, if you have a need for "variable variables", as it were, you would use a dict:通常,如果您需要“变量变量”,您可以使用 dict:

data = {
    foo: foo_value,
    bar: bar_value
}

And then use data[foo] instead of trying to use foo as a variable.然后使用data[foo]而不是尝试使用foo作为变量。 However, in this example you're actually asking about importing a module through a string, and about getting attributes using a string name, both of which are services Python provides: through the __import__ and getattr functions.但是,在这个示例中,您实际上是在询问如何通过字符串导入模块,以及使用字符串名称获取属性,这两者都是 Python 提供的服务:通过__import__getattr函数。

Members of a module are just attributes on that module, so you can use getattr on the module object to retrieve them.模块的成员只是该模块的属性,因此您可以在模块 object 上使用getattr来检索它们。

The module objects themselves are stored in the sys.modules dictionary:模块对象本身存储在sys.modules字典中:

module = sys.modules[modulename]
member = getattr(module, membername)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM