如何将字符串转换为变量名?
我想知道如何将字符串输入转换为变量名以用于Python代码。一个具体的例子:
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)
所以在上面,因为我不知道在启动之前要自省哪个模块,所以我需要将字符串转换为可用的模块名称,并且因为 getmembers()
将成员作为字符串返回,我还需要将它们转换为可用的变量名称以检查它们是否可调用。
有这样的makestringvariable()
函数吗?
I would like to know how to convert a string input into a variable name to use into Python code. 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.
Is there such a makestringvariable()
function?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使用 __import__ 函数和 getattr 魔法,你将能够直接写这个:
with the __import__ function and the getattr magic, you will be able to directly write this :
您无法将字符串本身转换为变量,因为变量是代码的一部分,而不是数据的一部分。通常,如果您需要“变量”,可以使用字典:
然后使用
data[foo]
而不是尝试使用foo
作为变量。然而,在这个例子中,您实际上是在询问如何通过字符串导入模块,以及如何使用字符串名称获取属性,这两者都是 Python 提供的服务:通过__import__
和getattr
函数。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:
And then use
data[foo]
instead of trying to usefoo
as a variable. 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__
andgetattr
functions.模块的成员只是该模块上的属性,因此您可以在模块对象上使用 getattr 来检索它们。
模块对象本身存储在 sys.modules 字典中:
Members of a module are just attributes on that module, so you can use
getattr
on the module object to retrieve them.The module objects themselves are stored in the
sys.modules
dictionary: