[Tutor] ".=" in Python ?

Jeff Shannon jeff@ccvcorp.com
Mon May 5 17:26:09 2003


Tadahiko 'kiko' Uehara wrote:

>Sorry I wasn't clear in my previous post(obviouslly, subject too)...
>
>perl:
>	my $a .= $a."text";
>	print $a;
>
>Python:
>	a = ""
>	a += a + "test"
>	print a
>
>I thought I did something unnatural so I needed to say 1st line 'a = ""'.
>Or Does it work like this?
>  
>

No, you didn't do anything unnatural -- that's the way that Python 
works.  It's a little bit more picky about creating variables than Perl is.

The += requires that the variable already exist, as does "a = a + b" 
(which is more or less equivalent).  Python only creates variables when 
you assign to them, i.e. when they're on the left side of an =.  

In both cases, the first time through you're asking your program to add 
"text" to something that doesn't exist yet.  The difference is that 
Python tells you "Hey, this doesn't exist -- are you sure you meant to 
do that?", whereas Perl says quietly to itself "Well, this doesn't 
exist, so I guess they might mean for this to be an empty string.  I'm 
gonna try that and hope that it's right."  This is a design difference 
between the languages -- Perl tries to guess your intent, while Python 
refuses to guess.  This means that Perl is less likely to complain... 
but it also means that Perl might guess *wrong*, and you'll never know 
unless you look *very* carefully.

In the Python example, by creating the empty string beforehand, you're 
telling Python exactly what you want to start off with.  That means that 
Python doesn't need to guess at what you meant by trying to use a 
nonexistent variable, so it has no need to complain.

Jeff Shannon
Technician/Programmer
Credit International