1

file1.py:

def test_globals():
    globals()['t']=5

in python3 repl:

>>> from file1 import *
>>> test_globals()
>>> t
Traceback ....
NameError: name 't' is not defined
>>> def test_globals2(): #local context
        globals()['t'] = 5
>>> test_globals2()
>>> t
5

How to fix test_globals function to actually modify globals()?

2
  • Generally, you don't want to do this. Modifying the current module's globals is confusing enough. Modifying another module's globals is way off the beaten path. It's probably possible to accomplish in a non-portable way by inspecting the stack, etc, etc. But before digging into it that deeply, you should probably ask whether this is really something you actually need to do... :-) Commented Nov 10, 2014 at 2:35
  • ok, I want to do this to reload functions from changed modules to repl during interactive development process. Commented Nov 10, 2014 at 2:40

1 Answer 1

1

The problem with what you did is that from file1 import * didn't import t because it didn't exist. If you repeat the import line, it will work:

>>> from file1 import *
>>> test_globals()
>>> t
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 't' is not defined
>>> from file1 import *
>>> t
5

Another thing that would work:

>>> import file1 as f1
>>> f1.t
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 't'
>>> f1.test_globals()
>>> f1.t
5

However, if you're only after reloading a module (as you wrote in the comments), consider using importlib.reload.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.