简体   繁体   中英

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.

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM