Thomas Baruchel
Thomas Baruchel

Reputation: 7517

How to get the globals from a module namespace?

Is there a way to get the dictionary containing the global variables in a specific module namespace? It looks that you can achieve it if the module contains at least one function with something like:

import mymodule
d = mymodule.func.__globals__

Is this right?

Is there a more general way? (For instance, how could this be done if the module wouldn't contain any function but only variables?)

I am not expecting a "What are you trying to do with that? There is probably another way of doing it." answer; my question is rather a theoretical one.

I am more interested here by a Python3 answer if it matters.

Upvotes: 10

Views: 7779

Answers (1)

Dimitris Fasarakis Hilliard
Dimitris Fasarakis Hilliard

Reputation: 160427

Just grab use vars which grabs its __dict__ which corresponds to the global scope.

vars(mymodule)

func.__globals__ simply returns this dictionary for you see how:

vars(mymodule) is mymodule.func.__globals__

returns True.

Upvotes: 23

Related Questions