Test None for an object that does not implement ==

Roy Smith roy at panix.com
Sun Dec 25 09:13:09 EST 2011


In article <mailman.4066.1324820148.27778.python-list at python.org>,
 Chris Angelico <rosuav at gmail.com> wrote:

> On Mon, Dec 26, 2011 at 12:17 AM, Roy Smith <roy at panix.com> wrote:
> > Just for fun, I tried playing around with subclassing NoneType and
> > writing an __eq__ for my subclass.  Turns out, you can't do that:
> >
> > Traceback (most recent call last):
> >  File "./none.py", line 5, in <module>
> >    class Nihil(NoneType):
> > TypeError: Error when calling the metaclass bases
> >    type 'NoneType' is not an acceptable base type
> 
> Yes; unfortunately quite a few Python built-in classes can't be
> subclassed. It's an unfortunate fact of implementation, I think,
> rather than a deliberate rule.
> 
> But then, what would you ever need to subclass None for, other than
> toys and testing?

You might be to differentiate between temporary and permanent failures.  
Let's say you have a WidgetPool, containing Widgets of various classes.

class WidgetPool:
   def get_widget(class_name):
      """Return a Widget of a given class.  If there are no such
      Widgets available, returns None."""
      [...]

You might want to return a None subclass to signify, "No such Widgets 
are currently available, but they might be if you try again in a little 
while", as opposed to "No such Widgets will ever be available".

If you were designing the interface from scratch, you would probably 
represent that with an exception hierarchy.  However, if this was an old 
interface that you were modifying, this might be a way to return a 
richer failure indication for new clients without breaking backwards 
compatibility for existing code.

Of course, the existing code would probably be using "is None" tests, 
and break anyway.  But at least that's a plausible scenario for None 
subclasses.



More information about the Python-list mailing list