tags:

views:

198

answers:

1

I'm currently reading chapter 5.8 of Dive Into Python and Mark Pilgrim says:

There are no constants in Python. Everything can be changed if you try hard enough. This fits with one of the core principles of Python: bad behavior should be discouraged but not banned. If you really want to change the value of None, you can do it, but don't come running to me when your code is impossible to debug.

I tried this in the interpreter

None = "bad"

I get a SyntaxError: assignment to None

Just out of curiosity how do you change None?

EDIT:

Interestingly:

>>> import __builtin__
>>> __builtin__.None is None
True
>>> None
>>> None = "bad"
  File "<stdin>", line 1
SyntaxError: assignment to None
>>> __builtin__.None = "bad"
  File "<stdin>", line 1
SyntaxError: assignment to None
>>> setattr(__builtin__, "None", "bad")
>>> __builtin__.None
'bad'
>>> None
>>> __builtin__.None is None
False
>>> __builtin__.None = None
  File "<stdin>", line 1
SyntaxError: assignment to None

Also

>>> class Abc:
...     def __init__(self):
...             self.None = None
... 
  File "<stdin>", line 3
SyntaxError: assignment to None
>>> class Abc:
...     def __init__(self):
...             setattr(self,'None',None)
... 
>>> 

So I guess 'None = ' just doesn't work in any context

+10  A: 

You first have to install an old version of Python (I think it needs to be 2.2 or older). In 2.4 and newer for certain (and I believe in 2.3) the assignment in question is a syntax error. Mark's excellent book is, alas, a bit dated by now.

Alex Martelli
I think 2.3 gave you a SyntaxWarning, fwiw.
perimosocordiae
Thanks for the reply, I guess there's no love for thugs anymore in the newer versions.
mike
You can still do `True = False` in 2.6 though. And it will have the effect you want.
viraptor
viraptor: I'm confused. What effect does one want when one says `True = False`?
Ken
@Ken Presumably to make the name "True" point to the value that the name "False" does (which is to say, the false boolean object). In other words, to destroy every ounce of sanity you have.
Devin Jeanpierre
Isn't it just for the scope in which the assignment took place?
wRAR
Yes, it is only in the local scope. The effect is: overwriting True. It's similar to what the question is about - overwriting stuff that one would not exactly expect to ever change the value.
viraptor