简体   繁体   中英

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. 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?

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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