Python 2.4: Why only assignments to None are forbiden?

David M. Cooke cookedm+news at physics.mcmaster.ca
Fri Nov 12 16:18:56 EST 2004


Josef Meile <jmeile at hotmail.com> writes:

> Hi,
>
> Textually from the highlights of python 2.4:
>
> "Assigning to None - the compiler now treats assigning to None as a
> SyntaxError."
>
> I think in general assignments to built-in types, functions, and
> variables should be also forbiden. It's a common mistake to do things
> like this:
>
>  >>> def getFileName(file):
> ...   parts=file.split('/')
> ...   return parts('/')[-1]

> Specially if you come from python 2.1.x where "file" didn't exist.
> Instead, there was "open"
>
> On the example's context, file is a string and won't cause any damage
> because it is inside a function, so, the scope is local and it will be
> deleted after the function call. But think what would happen if
> somebody defines "file" as a global variable and other people use that
> code?

That may not be great style, but it's not a mistake: file is used as a
local variable, so the global binding doesn't enter into it. And with
this short of function, I wouldn't worry too much.

Longer functions, yes, you might get bit, especially with other
builtins, like str and dict.

> Doing this validation for python 2.4.x will break some things, like
> the validation with "None" does. But I think it's better when you now
> that you are trying to use a "reserved word", you could as well use
> the "str" as an example, which I think is also common on newies.

I believe the idea behind making None non-assignable is one of
optimization: it's used a lot, and each time, the runtime has to do a
lookup to find the current value.

But making other builtins unassignable, while nice, removes some of
the dynamism that makes Python nice.

Recently, I needed to check what files my program was opening (and not
closing; I was running out of file descriptors). The easy way to do
that was to override the builtin open() function, returning a proxy
object that would annouce it's been opened, and when it's been closed.
This isn't quite the same thing: I had to assign to __builtin__.open
so that all modules would get my new open. However, if open were
declared unassignable, I'll bet you that it would be bound at
*compile* time instead of runtime, and this trick wouldn't work anyways.

-- 
|>|\/|<
/--------------------------------------------------------------------------\
|David M. Cooke
|cookedm(at)physics(dot)mcmaster(dot)ca



More information about the Python-list mailing list