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?
import mymodule var = getattr(mymodule, variablename)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With