variable declaration

Alex Martelli aleaxit at yahoo.com
Sat Feb 5 13:04:55 EST 2005


Nick Coghlan <ncoghlan at iinet.net.au> wrote:

> Alex Martelli wrote:
> > 'global' is an ugly wart, to all intents and purposes working "as if" it
> > was a declaration.  If I had to vote about the one worst formal defect
> > of Python, it would surely be 'global'.
> > 
> > Fortunately, it's reasonably easy to avoid the ugliness, by avoiding
> > rebinding (within functions) global variables, which tend to be easy.
> 
> Hear, hear! And if I could write "gbls = namespace(globals())" in order to
> deal with those rare cases where I *do* need to rebind globals, all uses
> of the keyword could be handled nicely, while entirely eliminating the
> need for the keyword itself.

I entirely agree with you on this.


> Would you be as violently opposed to a 'rebinding' augmented assignment
operator?

Not at all.  The only downside I can see, and it seems a minor one to
me, is having two "obvious ways" to re-bind a name, since '=' would keep
working for the purpose.  But making it explicit that one IS rebinding a
name rather than binding it anew could sometimes make certain code more
readable, I think; quite apart from possible advantages in catching
typos (which may be OK, but appear minor to me), the pure gain in
reaability might make it worth it.  Call my stance a +0.

> the problem of detecting typos in the right-most name in a compound name
(e.g.

It's not clear to me what semantics, exactly, x.y := z would be defined
to have (assuming := is the syntax sugar for ``rebinding'').  Perhaps,
by analogy with every other augmented operator, it should be equivalent
to:

    _temp = x.y
    x.y = type(temp).__irebind__(temp, z)

This makes it crystal-clear what happens when type(x).y is a descriptor
with/without __set__ and __get__, when type(x) defines __getattribute__
or __setattr__, etc, etc.  Giving type object an __irebind__ which just
returns the second operand would complete the semantics.  Of course,
doing it this way would open the issue of types overriding __irebind__,
and it's not clear to me that this is intended, or desirable.  So, maybe
some other semantics should be the definition.  But since "rebinding" is
not a primitive, the semantics do need to be somehow defined in terms of
elementary operations of getting and setting (of attributes, items, &c).

> Did I mention the possible incidental benefit of reducing the whinging
> about the lack of variable declarations?

It might, with some luck;-).  Probably worth a PEP, although I suspect
it will not be considered before 3.0.


Alex



More information about the Python-list mailing list