简体   繁体   中英

How can I tell whether a variable is global or local?

如何判断Python中的变量是全局变量还是局部变量?

globals() will return a dict of global variables

locals() will return a dict of local variables

to check if the scope of the variable:

if 'variable' in locals(): print("It's local") #Replace 'variable' with the variable
elif 'variable' in globals(): print("It's global") #But keep the quotation marks
else: print("It's not defined")

If you don't know about scopes, heres a good page to go to https://stackoverflow.com/a/292502/7486769

If all you are doing is making a list for some documentation, all you need to do is create a list of variables that are defined outside of any function or class.

var1 = "something"

def foo():
    var2 = "something"

In the above, var1 is global, var2 is local.

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