[Python-Dev] new draft of PEP 227
Paul Prescod
paul@prescod.net
Wed, 13 Dec 2000 23:57:30 -0800
Tim Peters wrote:
>
> ...
>
> I've rarely seen problems due to shadowing a global, but have often seen
> problems due to shadowing a builtin.
Really?
I think that there are two different issues here. One is consciously
choosing to create a new variable but not understanding that there
already exists a variable by that name. (i.e. str, list).
Another is trying to assign to a global but actually shadowing it. There
is no way that anyone coming from another language is going to consider
this transcript reasonable:
>>> a=5
>>> def show():
... print a
...
>>> def set(val):
... a=val
...
>>> a
5
>>> show()
5
>>> set(10)
>>> show()
5
It doesn't seem to make any sense. My solution is to make the assignment
in "set" illegal unless you add a declaration that says: "No, really. I
mean it. Override that sucker." As the PEP points out, overriding is
seldom a good idea so the requirement to declare would be rarely
invoked.
Actually, one could argue that there is no good reason to even *allow*
the shadowing of globals. You can always add an underscore to the end of
the variable name to disambiguate.
> Alas, if this rule were extended to
> builtins too-- where it would do the most good --then the names of builtins
> would effectively become reserved words (any code shadowing them today would
> be broken until declarations were added, and any code working today may
> break tomorrow if a new builtin were introduced that happened to have the
> same name as a local).
I have no good solutions to the shadowing-builtins accidently problem.
But I will say that those sorts of problems are typically less subtle:
str = "abcdef"
...
str(5) # You'll get a pretty good error message here!
The "right answer" in terms of namespace theory is to consistently refer
to builtins with a prefix (whether "__builtins__" or "$") but that's
pretty unpalatable from an aesthetic point of view.
Paul Prescod