简体   繁体   中英

Python accessing global variables using globals()

Look into below example..

var1 = 10
var2 = "String"
var3 = True
dic = {}

def func1():
  ...
  ...

def main():
  varN = globals().["var1"]
  Dictionary = globals().["dic"].var2('some other string')

How to read this ? globals () ? how is this being used and interpreted ?

Please Help. Thanks.

globals() returns a dictionary.

print type(globals())  # <type 'dict'>

So, subscript notation is enough to access the global variables.

print globals()["var1"]
globals()["dic"][var2] = 'some other string'
print dic   # {'String': 'some other string'}

globals is a built in python function it's always available
see: http://docs.python.org/2/library/functions.html#globals

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM