Python 2.4: Why only assignments to None are forbiden?
Ian Bicking
ianb at colorstudy.com
Fri Nov 12 16:48:20 EST 2004
Josef Meile wrote:
> 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"
Well, it's not really a mistake, because it works just fine and causes
no problems. I use builtin names often, as they are annoyingly very
convenient local variables. I try not to, but it still happens
(especially file, though I make sure to distinguish between files and
filenames).
Anyway, it's a big backward compatibility issue. No one ever reassigns
None, so it's not a problem. Maybe True and False will go this way too
(though that *will* cause backward compatible problems with code that
preceded the True/False builtins, and so created its own True/False
objects).
> 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? For
> the author won't be any consequences at all, because if s/he does this,
> it means that probably s/he isn't working with files, but if somebody
> else takes that code and doesn't see this, then s/he will invest some
> time trying to find the bug.
There are proposed optimizations that depend on there being no
global-level redefinition of builtins, and there's a couple PEPs about
this. I think the ideas have been viewed favorably, but the
implementations haven't been fully fleshed out, and kind of fell by the
wayside. They could still be picked up. There were a few people who
were concerned; I think boost particularly defines some public symbols
like boost.int, which this would disallow.
Anyway, the much more conservative proposal that disallows global
variables that share a name with a builtins seems reasonable and largely
backward compatible.
--
Ian Bicking / ianb at colorstudy.com / http://blog.ianbicking.org
More information about the Python-list
mailing list