variable declaration

Nick Coghlan ncoghlan at iinet.net.au
Thu Feb 10 07:49:39 EST 2005


Antoon Pardon wrote:
> Well it seems you have some fair points. I'll just stop here stating
> that I would like to have it, even if it proved to be slower. Speed
> is not that big a factor in the things I write.

Oh, certainly. I wasn't suggesting the speed hit was enough to kill the idea - I 
was just pointing it was something that you would use when correctness and being 
explicit was considered more important than a small price in speed. And if the 
name check got optimised out like an assert does. . . Hey, that gives me an idea 
(see below).

> I just would like
> to ask a question relating semantics. Supose the following code.
> 
> x = 42
> 
> def f():
>   x := 21   #  or x .= 42  I don't remember what you used exactly

Alex used ':=' in a couple of examples, but you'll have to ask him his reasons.

I used '.=' instead mainly because I think colons are ugly, but also because 
':=' has the ability to trigger confusion due to its slightly different use in 
those languages which use it for assignment (Eiffel and Pascal come to mind. . . 
since Pascal uses it, I guess Delphi does too).

> What do you feel should happen. I can think of two possibilities.
> 
> 1) It raises an exception because x is not locally bound.
> 
> 2) it prints 21.
> 
> 
> I think the second option would be the more interesting one as
> it would allow to get rid of the global statement and it would
> allow for rebinding names within nested scopes.

I was thinking of the simpler version, with x .= 21 meaning roughly:

   assert x or True # This will blow up if x fails to resolve
   x = 21

The assertion would then blow up in your example (because x is an as yet unbound 
local variable). To my mind, this follows the principle of least surprise.

I think the globals issue is better handled via the generic objects PEP, with an 
alternate constructor that allows the generic object to be used to alter an 
existing dictionary. Apply the trick to globals() and you're done.

And if Python were to ever acquire some sort of 'scope()' function to allow 
programmatic access to scopes other than globals, generic objects would work for 
using those, too.

Cheers,
Nick.

-- 
Nick Coghlan   |   ncoghlan at email.com   |   Brisbane, Australia
---------------------------------------------------------------
             http://boredomandlaziness.skystorm.net



More information about the Python-list mailing list