Ad

If An Object Exist, Take An Action In Python

- 1 answer

I'm very new to python and I'm trying to make an if then statement as the one used in Delphi. I looked at other posts about this but all the examples I've encountered are with "print". I have an object that I want to handle if appears, for example if object(name_mapping) exists then take action x and action y. Can somebody help me?

if (object_mapping) is not none:

Ad

Answer

There are several ways you can approach this, this first and recommended one is using a dictionary. Have a dictionary that you use for your dynamically defined objects

object_mapping = {}
object_mapping['my_object'] = 42

    if 'my_object' in object_mapping:
        # do this if the object is defined
        pass
    else:
        #do this if the object is NOT defined
        pass


The other way of doing this, and its not wise to use this, is using try catch blocks

try:
    do_stuff(object_mapping) # will only run if object_mapping is defined
except NameError:
    #will only run if object_mapping is NOT defined
    pass
Ad
source: stackoverflow.com
Ad