[Tutor] Null Object Design Pattern Question

Gonçalo Rodrigues op73418 at mail.telepac.pt
Sun Jun 13 16:55:07 EDT 2004

Em Sun, 13 Jun 2004 08:59:10 -0800, Tim Johnson <tim at johnsons-web.com>
atirou este peixe aos pinguins:

>I have been looking at 
>which has an example of using a Null() object.
>Unfortunately, I'm having a problem wrapping my brain around
>the usefulness of this object compared to just using None.
>Does anyone have some further examples of the 'superiority'
>of this approach over *None*.

Imagine a null object as a kind of sink: it responds to all messages
without barfing. Compare the following:

>>> obj = None
>>> obj.method()
Traceback (most recent call last):
  File "<interactive input>", line 1, in ?
AttributeError: 'NoneType' object has no attribute 'method'

>>> class Null(object):
... 	def __call__(self, *args, **kwargs):
... 		return self
... 	def __getattr__(self, attrib):
... 		return self
>>> obj = Null()
>>> obj.method()
<__main__.Null object at 0x00EFECF0>

The Null() doesn't barf when method is called. This allows for simpler
coding in some situations.

With my best regards,
G. Rodrigues

P.S: Googling for "null object pattern" (or some such) is bound to
turn up something.

More information about the Tutor mailing list