variable declaration

Nick Coghlan ncoghlan at iinet.net.au
Sat Feb 5 11:54:03 EST 2005


Alexander Zatvornitskiy wrote:
> var epsilon=0
> var S
> S=0
> while epsilon<10:
>   S=S+epsilon
>   epselon=epsilon+1#interpreter should show error here,if it's in "strict mode"
> print S
> 
> It is easy, and clean-looking.
> 
> Alexander, zatv at bk.ru

An alternate proposal, where the decision to request rebinding semantics is made 
at the point of assignment:

epsilon = 0
S = 0
while epsilon < 10:
   S .= S + epsilon
   epselon .= epsilon + 1 #interpreter should show error here
print S

Of course, this is a bad example, since '+= ' can be used already:

S = 0
epsilon = 0
while epsilon<10:
   S += epsilon
   epselon += 1 #interpreter DOES show error here
print S

However, here's an example where there is currently no way to make the rebinding 
intent explicit:

def collapse(iterable):
     it = iter(iterable)
     lastitem = it.next()
     yield lastitem
     for item in it:
         if item != lastitem:
             yield item
             lastitem = item

With a rebinding operator, the intent of the last line can be made explicit:

def collapse(iterable):
     it = iter(iterable)
     lastitem = it.next()
     yield lastitem
     for item in it:
         if item != lastitem:
             yield item
             lastitem .= item

(Note that doing this *will* slow the code down, though, since it has to check 
for the existence of the name before rebinding it)

Cheers,
Nick.

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



More information about the Python-list mailing list