Return value of an assignment statement?

Carl Banks pavlovevidence at gmail.com
Fri Feb 22 11:19:07 EST 2008


On Feb 22, 9:58 am, Steven D'Aprano <st... at REMOVE-THIS-
cybersource.com.au> wrote:
> On Fri, 22 Feb 2008 00:45:59 -0800, Carl Banks wrote:
> > On Feb 21, 6:52 pm, Steve Holden <st... at holdenweb.com> wrote:
> >> mrstephengross wrote:
> >> >> What you can't do (that I really miss) is have a tree of
> >> >> assign-and-test expressions:
> >> >>         import re
> >> >>         pat = re.compile('some pattern')
> >> >>         if m = pat.match(some_string):
> >> >>             do_something(m)
>
> >> > Yep, this is exactly what I am (was) trying to do. Oh well.... Any
> >> > clever ideas on this front?
>
> >> The syntax is the way it is precisely to discourage that kind of clever
> >> idea.
>
> > Don't be ridiculous.  Assignment operators are maybe one of the worst
> > things in existence, but this particular use case (running a sequence of
> > tests like the above) is perfectly useful and good.
>
> I don't understand your reasoning. If assignment operators are so
> terrible, why do you think the terribleness disappears in this specific
> case?

I don't.

The assignment operator is terrible but the idiom itself isn't.


[snip narrowly applicable counterexamples that don't really mean
anything because they're too narrow]

> Perl's treatment of assignment as an operator tempts the programmer to
> write quick-and-dirty code.

(The perl example wasn't using an assignment operator.)

> Python discourages that sort of behaviour,
> and encourages programmers to factor their code in a structured way.
> That's a feature, not a bug.

The set-and-test idiom is not necessarily quick and dirty, and for
many things it's more readable and a lot easier to follow than any of
indirect methods that are proposed.

The fact that sometimes an assignment operator is used to do this
doesn't change the usefulness of the idiom itself.

It can be done without assignment expressions.  I gave a hypothetical
syntax for how it might be done in Python without them.

I can't help but to think that a lot of people's distaste for this
natural way to write certain logic is simply defensiveness about one
minor little thing that Python doesn't support (without workarounds).


Carl Banks



More information about the Python-list mailing list