Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 875
Thomas Baruchel Avatar asked Dec 29 '16 22:12

Thomas Baruchel


Video Answer


1 Answers

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.

like image 166
Dimitris Fasarakis Hilliard Avatar answered Sep 29 '22 08:09

Dimitris Fasarakis Hilliard