How to use imported function to get current globals

Ian Kelly ian.g.kelly at gmail.com
Sat Jun 7 13:57:46 EDT 2014


On Sat, Jun 7, 2014 at 11:40 AM, 1989lzhh <1989lzhh at gmail.com> wrote:
> Here is the code
> m1.py
> def f():
>     print globals()
>
> m2.py
> from m1 import f
> f()# how to get current module's globals?

Evaluate globals() in the current module and pass the resulting dict
in as a parameter:

# m1.py
def f(globals):
    print globals

# m2.py
from m1 import f
f(globals())

There's a code smell here, though.  If your function really needs to
interact with globals from other modules, then those should probably
not be globals in the first place.  More likely they should be
attributes of objects that can be easily passed around.



More information about the Python-list mailing list