Reputation: 26437
I'm trying to find a way to access module variable by name, but haven't found anything yet. The thing I'm using now is:
var = eval('myModule.%s' % (variableName))
but it's fuzzy and breaks IDE error checking (i.e. in eclipse/pydev import myModule is marked as unused, while it's needed for above line). Is there any better way to do it? Possibly a module built-in function I don't know?
Upvotes: 30
Views: 20042
Reputation: 2795
If you want to get a variable from the current module you're running in (and not another one):
import sys
# sys.modules[__name__] is the instance of the current module
var = getattr(sys.modules[__name__], 'var_name')
var
can be of course a regualr variable, class or you anything else basically :)
Upvotes: 4
Reputation: 125
Another option, is to use INSPECT, and the getmembers(modulename) function.
It will return a complete list of what is in the module, which then can be cached. eg.
>>>cache = dict(inspect.getmembers(module))
>>>cache["__name__"]
Pyfile1 test
>>>cache["__email__"]
'[email protected]'
>>>cache["test"]("abcdef")
test, abcdef
The advantage here is that you are only performing the look up once, and it assumes that the module is not changing during the program execution.
Upvotes: 2
Reputation: 1141
getattr(themodule, "attribute_name", None)
The third argument is the default value if the attribute does not exist.
From https://docs.python.org/2/library/functions.html#getattr
Return the value of the named attribute of object. name must be a string. If the string is the name of one of the object’s attributes, the result is the value of that attribute. For example, getattr(x, 'foobar') is equivalent to x.foobar. If the named attribute does not exist, default is returned if provided, otherwise AttributeError is raised.
Upvotes: 10