Assignment and comparison in one statement
Paul McGuire
ptmcg at austin.rr.com
Sat May 24 09:58:38 EDT 2008
On May 24, 6:12 am, Johannes Bauer <dfnsonfsdu... at gmx.de> wrote:
> Carl Banks schrieb:
>
> > p = myfunction()
> > if p:
> > print p
>
> > (I recommend doing it this way in C, too.)
>
> This is okay for if-clauses, but sucks for while-loops:
>
> while (fgets(buf, sizeof(buf), f)) {
> printf("%s\n", buf);
>
> }
>
> is much shorter than
>
> char *tmp;
> tmp = fgets(buf, sizeof(buf), f);
> while (tmp) {
> printf("%s\n", buf);
> tmp = fgets(buf, sizeof(buf), f);
>
> }
> > For the case where you want to do this in an elif-clause, look for the
> > recent thread "C-like assignment expression?" which list some
> > workarounds. Or just Google this newsgroup for "assignment
> > expression". It's one of few minor irritating things in Python
> > syntax.
>
> Alright, I will. Thanks.
>
> Regards,
> Johannes
>
> --
> "Wer etwas kritisiert muss es noch lange nicht selber besser können. Es
> reicht zu wissen, daß andere es besser können und andere es auch
> besser machen um einen Vergleich zu bringen." - Wolfgang Gerber
> in de.sci.electronics <47fa8447$0$11545$9b622... at news.freenet.de>
I posted this to the other thread, but I'm afraid it might get buried
over there. See if this works for you.
class TestValue(object):
"""Class to support assignment and test in single operation"""
def __init__(self,v=None):
self.value = v
"""Add support for quasi-assignment syntax using '<<' in place of
'='."""
def __lshift__(self,other):
self.value = other
return self
def __bool__(self):
return bool(self.value)
__nonzero__ = __bool__
import re
tv = TestValue()
integer = re.compile(r"[-+]?\d+")
real = re.compile(r"[-+]?\d*\.\d+")
word = re.compile(r"\w+")
for inputValue in ("123 abc -3.1".split()):
if (tv << real.match(inputValue)):
print "Real", float(tv.value.group())
elif (tv << integer.match(inputValue)):
print "Integer", int(tv.value.group())
elif (tv << word.match(inputValue)):
print "Word", tv.value.group()
Prints:
Integer 123
Word abc
Real -3.1
In your examples, this could look like:
tv = TestValue()
while (tv << fgets(buf, sizeof(buf), f)) {
printf("%s\n", tv.value);
or:
if (tv << myfunction()):
What do you think? Is '<<' close enough to '=' for you?
-- Paul
More information about the Python-list
mailing list