Why globals () inside a function cannot update variables in an interactive shell?

Today I wrote the "alias import" function for myself, because I need to write a script to check the values โ€‹โ€‹of variables for different python files.

# filename: zen_basic.py

import importlib
def from_module_import_alias(module_name, var_name, alias):
    """ equal to from module import a as b """
    agent = importlib.import_module(module_name)
    globals()[alias] = vars(agent)[var_name]

It is strange if I run the interactive Python shell, I cannot import things using this function. But using its content outside the function, it works.

>>> from zen_basic import *
>>> module_name = 'autor'
>>> var_name = 'food'
>>> alias = 'fd'
>>> from_module_import_alias(moduele_name, var_name, alias)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'moduele_name' is not defined
>>> from_module_import_alias(module_name, var_name, alias)
>>> fd
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'fd' is not defined
>>> agent = importlib.import_module(module_name)
>>> globals()[alias] = vars(agent)[var_name]
>>> fd
'cake'
>>>

I did 3 more experiments after:

    • Do python -i test.py
    • import zen_basic in an interactive shell Function
    • call from_module_import_aliasfailed.
    • Do python -i zen_basic.py
    • challenge from_module_import_aliasfunction, success.
    • add the code which import zen_basic, and call from_module_import_alias functionintest.py
    • Do python -i test.pysuccess

What is the reason that it was not possible to directly use the function from_module_import_aliasin the Python interactive shell?

+4
1

. zen_basic, __main__ ( script ). globals() , , , .

. , , , sys._getframe():

import sys

def from_module_import_alias(module_name, var_name, alias):
    """ equal to from module import a as b """
    agent = importlib.import_module(module_name)
    calling_globals = sys._getframe(1).f_globals
    calling_globals[alias] = vars(agent)[var_name]

python -i zen_basic.py zen_basic script, globals() __main__.

+5

All Articles