No "side effect" assignment!

John Roth newsgroups at jhrothjr.com
Sun Sep 14 18:41:43 EDT 2003


"Tobiah" <toby at rcsreg.com> wrote in message
news:0fbc28ebd2ba4810db3efef3a29f990a at news.teranews.com...
> Ok,
>
> I miss the idiom that my other languages use,
> something like:
>
>
> while( foo = getmore()){
> process(foo);
> }
>
>
> I can't seem to do this in python without gagging:
>
> foo = getmore()
> while foo:
> process(foo)
> foo = getmore()
>
>
> Is that what ppl do?  The manual sez that this is
> so that newbs won't do:
>
> if foo = bar:
> process()
>
> thinking that they are checking for equality.
> I feel that in a few ways python suffers by catering
> to the uninitiated.  Usually however, there are
> great workarounds (or even plain better ways to do the job),
> which I am hopeful will be yielded by the list, as has
> been it's record thus far to do.

While one of Guido's reasons for not including assignment
as an expression was to avoid errors (and that's not always
a novice error,) Python provides similar functionality in the
'for' statement. In C, C++ and Java, 'for' is basically
syntactic sugar around a loop, in Python, it actually does
an assignment of the next element of a sequence.

Your example could be:

for foo in getmore:
    process(foo)

as long as getmore is either a sequence or implements the
iterator protocol.

This isn't a total replacement for assignment as an expression,
but it does cover the overwhelming majority of use cases.

John Roth


>
> Thanks,
>
> Tobiah
>






More information about the Python-list mailing list