简体   繁体   中英

python: Creating a function that receives a global variable as parameter and tests if it is defined

I have the following problem: In a Python module, I have a few global variables and instead of the usual try - except for each one of them, I want to test if they are defined using one general function. I thought of this:

def isDefined(variable):    
    try:
        variable
        return True        
    except NameError as error:        
        return False

but it does not work. Does anyone have an idea how to do it? Thanks!

Of course you have to pass your variable in as a string - else it will always raise a NameError.

The globals built-in in python returns the module dictionary - global variables are stored in it.

def is_defined(variable):
    return variable in globals()

tomato = 42

is_defined ("tomato")

(If for some reason you think you can't have your variable name as a string, add some more context information, so I can tune the answer accordingly.)

To set a global variable with a default value:

def set_var(variable, value=0):
     globals()[variable] = value

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