I want a variable that represents either:
- the attribute of an object, or
- None, if the object doesn't exist.
Is there a better way to write that than:
object = some_function(thing)
value = object.value if object else None
I want a variable that represents either:
Is there a better way to write that than:
|
|||
Yes, there is one:
In your case the usage is:
|
|||||||
|
One way:
But its not easy to see what is happening there so I don't really recommend it. One option is to use to NullObject pattern. The idea is that you shouldn't use None. Instead, you should use an object which provides the null behavior. Your example would become
Where some_function returns a Null object that has a value attribute with whatever the default you want is. Relevant reading: |
|||||
|
AttributeError
as an alternative, though I wouldn't say that it would be better to do that in this case. – Jeff Mercado Jan 12 '12 at 0:55