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
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).
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.
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.
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 tox.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?.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With