Python Forum
Sys module - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Sys module (/thread-19698.html)



Sys module - Uchikago - Jul-11-2019

can any body explain why this didn't work
#test1.py
var=99
def glob3():
    var=0
    import sys
    glob=sys.modules['test1']
    glob.var+=1
glob3()
print(var)      #python report an error
But when i import that test1 module in interactive prompt, it worked:
>>> import test1
100



RE: Sys module - Gribouillis - Jul-11-2019

Because when you run the file without importing it, the variable __name__ has value '__main__' instead of 'test1' and the module is sys.modules['__main__']. You could use
glob = sys.modules[__name__]
However, this is strange python code. Why do you want to do this?


RE: Sys module - Uchikago - Jul-11-2019

(Jul-11-2019, 05:17 AM)Gribouillis Wrote: Why do you want to do this?
I'm just experimenting alternative way to use global variable


RE: Sys module - Gribouillis - Jul-11-2019

Uchikago Wrote:I'm just experimenting alternative way to use global variable
The best way is not to update global variables from functions. On the other hand, global variables can be mutable objects such as dictionaries or lists. This way you don't need the global statement.