Python Forum

Full Version: Sys module
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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
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?
(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
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.