[Tutor] How to perform variable assignment and

Steve Willoughby steve at alchemy.com
Sun Oct 4 01:55:27 CEST 2009

Oxymoron wrote:
> While having an assignment as an expression could be convenient in
> places (I have had my moments where I wish it was!), that particular
> usage is also a source of common bugs. Often in conditional statements

Me, too.  I grumble every time I have to take two separate statements
to assign then test, but this is an explicit design decision in Python
and I have to admit this *is* a frequent source of bugs.  Even in your
code, does
   if ($home = $ENV{HOME}) { ... }
mean to assign the value to $home and continue with the block if
that's a true value, or did you intend to do the block if some existing
variable $home is equal to $HOME in the environment?  The answer to that
is really non-obvious without reading a bit of the surrounding context.

Something more explicit like
   if (($home = $ENV{HOME}) ne '') { ...}
   if (defined($home = $ENV{HOME})) { ... }
is much more obvious that you knew what you were doing in putting the
assignment in there.

Even so, this seems to be a pitfall for many programmers, particularly
novices, and our BDFL decided to just make it a non-issue in Python, so
you have to be a tad more explicit, which in the bigger picture of code
maintainability, isn't really such a bad thing.

> My Perl is rusty at best! Not sure if there's an == operator, if there

Yes there is, although it would be incorrect to use here.  Now if you
want an even better example at why being explicit, and being strongly
typed, leads to more clarity in your code, this aspect of Perl is a good
one.  Since it's weakly typed, the operator used implicitly casts the
operands' types, so ($home == $ENV{HOME}) would silently force both
variables to *numeric* and return true if they returned the same numeric
value, so most strings (which evaluate to 0) would look "equal" there.
You need to say ($home eq $ENV{HOME}) would force both to be strings
and compare them for string equality.

Not trying to start a language war (I like and regularly use both Python
and Perl), but it shows some of the differences you see when one
language is specifically designed to make code very clear and explicit
and another wasn't.


More information about the Tutor mailing list