Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Sys module
#1
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
Reply
#2
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?
Reply
#3
(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
Reply
#4
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.
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020