Tell me more ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

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
share|improve this question
You can catch the 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

2 Answers

up vote 6 down vote accepted

Yes, there is one:

In [1]: getattr?
Type:       builtin_function_or_method
Base Class: <type 'builtin_function_or_method'>
String Form:<built-in function getattr>
Namespace:  Python builtin
Docstring:
getattr(object, name[, default]) -> value

Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.
When a default argument is given, it is returned when the attribute doesn't
exist; without it, an exception is raised in that case.

In your case the usage is:

obj = None
default_value = None

# This raises AttributeError:
value = getattr(obj, 'attr')  # is equal to: value = None.attr

# And this does not:
value = getattr(obj, 'attr', default_value)
share|improve this answer
1  
You should not that it has some dangers, in that misspelling 'attr' will produce a hard to find bug. – Winston Ewert Jan 12 '12 at 15:11
@WinstonEwert True. – Misha Akovantsev Jan 13 '12 at 1:52

One way:

value = object and object.value

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

object = some_function(thing)
value = object.value

Where some_function returns a Null object that has a value attribute with whatever the default you want is.

Relevant reading:

  1. http://en.wikipedia.org/wiki/Null_Object_pattern
  2. http://cs.oberlin.edu/~jwalker/nullObjPattern/
  3. http://c2.com/cgi/wiki?NullObject
share|improve this answer
1  
Note the minor difference between the OP and object and object.value is that it will pass through False-ish "object" values like False, [] and "" and 0 rather than strictly substitute None, for better or worse... +1 Null Object Pattern, so if you don't have control over some_function implementation, adapt it with object = some_function(thing) or none_valued_object – Paul Martel Jan 12 '12 at 6:13

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.