Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Get Property if Object is not None

Is there a Pythonic way to grab a property if an object exists on one line of code? Currently in the code below if someone passes in a None type object the code will break, so I need some clean way to check that it is not None, but on one line of code. C# has the ?. syntax that works really well, so looking for something like that.

class MyClass:
    def __init__():
        self.my_property = "Hello, World!"

def print_class_property(myClassInstance):
    print(myClassInstance???.my_property) # Here is where I need something inline
like image 909
CamJohnson26 Avatar asked Sep 06 '17 23:09

CamJohnson26


People also ask

How do you check if an object is not none in Python?

Use the is not operator to check if a variable is not None in Python, e.g. if my_var is not None: . The is not operator returns True if the values on the left-hand and right-hand sides don't point to the same object (same location in memory).

What does not none mean in Python?

It's often used as the default value for optional parameters, as in: def sort(key=None): if key is not None: # do something with the argument else: # argument was omitted. If you only used if key: here, then an argument which evaluated to false would not be considered.

What does if none do in Python?

The None keyword is used to define a null value, or no value at all. None is not the same as 0, False, or an empty string. None is a data type of its own (NoneType) and only None can be None.


1 Answers

You can use the built-in function getattr. It allows an optional third argument that will be returned if the object passed in doesn't have the specified attribute. From the docs:

getattr(object, name[, default])

Return the value of the named attribute of object. name must be a string. If the string is the name of one of the object’s attributes, the result is the value of that attribute. For example, getattr(x, 'foobar') is equivalent to x.foobar. If the named attribute does not exist, default is returned if provided, otherwise AttributeError is raised.

Bold emphasis mine.

>>> getattr(None, 'attr', 'default')
'default'

Here's an example pertaining more to your problem:

>>> class Class:
    def __init__(self):
        self.attr = 'attr'

        
>>> def func(obj):
    return getattr(obj, 'attr', 'default')

>>> func(Class())
'attr'
>>> func(None)
'default'

As @juanpa.arrivillaga said in the comments, another common idiom when dealing with cases such as this is to use try/except. See What is the EAFP principle in Python?.

like image 76
Christian Dean Avatar answered Oct 05 '22 22:10

Christian Dean