开发者

How to convert string to variable name?

开发者 https://www.devze.com 2023-03-08 01:50 出处:网络
I would like to know how to convert a string input into a variable name to use into Python code. A concrete example:

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)
开发者_如何学Go

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?


with the __import__ function and the getattr magic, you will be able to directly write this :

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:

data = {
    foo: foo_value,
    bar: bar_value
}

And then use data[foo] instead of trying to use foo 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__ and getattr functions.


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:

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

精彩评论

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