Alexander
Alexander

Reputation: 355

Using vars() for variable names from imported modules?

I am trying to do something like

import module_name
something = vars()["module_name.var_name"]

On program execution, I get

KeyError: 'module_name.var_name'

i.e. It doesn't work. Any way I can make it work?

Upvotes: 0

Views: 81

Answers (2)

match
match

Reputation: 11070

vars() with no argument works 'locally'. If you want to look at variables in another module, you need to pass that module as the argument:

vars(module_name)

You can then find a specific variable using []

vars(module_name)['var_name']

Upvotes: 1

Mogi
Mogi

Reputation: 614

This might solve it:

dir(vars()['module_name'])['var_name']

If not, I suggest you to explain about what you're trying to do and not about this specific problem

Upvotes: 0

Related Questions