Python 2.4: Why only assignments to None are forbiden?

Andrew Dalke adalke at mindspring.com
Sat Nov 13 16:47:54 EST 2004


Peter Hansen wrote:
> One perfectly good reason to assign to builtins (and there are others, 
> I'm sure) is to provide a "mock" function to replace a standard
> one, for use during automated testing.

That's understandable, but it doesn't work for None.  At the C
level there is a Py_None object which is the same singleton object
used by None.  If you replace the builtin None with a mock None
then almost certainly there will be strange effects.

Eg,

def spam():
   print "Here there be Vikings"

x = spam()

At this point, x contains the real None and not the mock one.

class MyList(list):
   def get(self, item):
     if item.startswith("__"):
       raise AccessDenied(item)
     return list.get(item)

x = MyList().get("wensleydale")


Again, x is the real None object and not the mock one.

So if reasonable code did the following

if x is None:
   print "Sorry, not even wensleydale"
else:
   print "Yes, we have it"

then it would break under the mock None case.

In theory it could be possible to make this work.  Setting
None in builtins could change some sort of proxy object at
the C level, and ... though the object ids wouldn't be right.
Hmmm.  It would be a lot of work for very, very little gain.

So while we do have

   Special cases aren't special enough to break the rules.

it's more than trumped by

   Although practicality beats purity.

It's almost impossible to make a proxy None object work
correctly.

In a related topic, would you like to have a proxy for the
numbers 0, 1, 2, etc.?  Is None special because it's a
variable name that cannot be reassigned or is it not special
because it's just like other builtin objects that cannot
be replaced by user-defined objects?

				Andrew
				dalke at dalkescientific.com



More information about the Python-list mailing list