Python gets a module variable by name

I am trying to find a way to access a module variable by name, but have not found anything yet. Now I use the following:

var = eval('myModule.%s' % (variableName)) 

but it is fuzzy and interrupts IDE error checking (i.e. in eclipse / pydev import myModule is marked as unused, while for the line above). Is there a better way to do this? Perhaps the built-in function of the module I do not know?

+14
variables python module
source share
3 answers
 import mymodule var = getattr(mymodule, variablename) 
+28
source share

getattr(themodule, "attribute_name", None)

The third argument is the default if the attribute does not exist.

From https://docs.python.org/2/library/functions.html#getattr

Return the value of the named attribute of the object. name must be a string. If the string is the name of one of the object attributes, the result is the value of this attribute. For example, getattr (x, 'foobar') is equivalent to x.foobar. If the named attribute does not exist, the default value is returned, if provided, otherwise an AttributeError is raised.

+5
source share

Another option is to use INSPECT and the getmembers (modulename) function.

It will return a complete list of what is in the module, which can then be cached. eg.

 >>>cache = dict(inspect.getmembers(module)) >>>cache["__name__"] Pyfile1 test >>>cache["__email__"] ' name@email.com ' >>>cache["test"]("abcdef") test, abcdef 

The advantage here is that you search only once, and it is assumed that the module does not change during program execution.

0
source share

All Articles