Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python get module variable by name

Tags:

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?

like image 242
ducin Avatar asked Feb 25 '14 10:02

ducin


2 Answers

import mymodule  var = getattr(mymodule, variablename) 
like image 148
Jayanth Koushik Avatar answered Oct 11 '22 17:10

Jayanth Koushik


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.

like image 41
cchi Avatar answered Oct 11 '22 19:10

cchi