Assignment and comparison in one statement

J

Johannes Bauer

Hello group,

I'm just starting with Python and am extremely unexperienced with it so
far. Having a strong C/C++ background, I wish to do something like

if (q = getchar()) {
printf("%d\n", q);
}

or translated to Python:

if (p = myfunction()):
print p

However, this "assignment and comparison" is not working. What's the
"Python way" of doing this kind of thing?

Thanks a lot,
Johannes
 
C

Carl Banks

Hello group,

I'm just starting with Python and am extremely unexperienced with it so
far. Having a strong C/C++ background, I wish to do something like

if (q = getchar()) {
printf("%d\n", q);

}

or translated to Python:

if (p = myfunction()):
print p

However, this "assignment and comparison" is not working. What's the
"Python way" of doing this kind of thing?


p = myfunction()
if p:
print p

(I recommend doing it this way in C, too.)

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.


Carl Banks
 
G

George Sakkis

Hello group,

I'm just starting with Python and am extremely unexperienced with it so
far. Having a strong C/C++ background, I wish to do something like

if (q = getchar()) {
        printf("%d\n", q);

}

or translated to Python:

if (p = myfunction()):
        print p

However, this "assignment and comparison" is not working. What's the
"Python way" of doing this kind of thing?

The most obvious and readable of course: use two statements, as one
should do regardless of the language, instead of resorting to error-
prone hacks.

George
 
T

TheSaint

However, this "assignment and comparison" is not working. What's the
"Python way" of doing this kind of thing?

If you want speak a language that isn't understood mostly you'll face
unexpected risults.
When you got started with C/C++, were you writing plain english to do
programs?
Far away to be a flame, each language have its own grammar that some time it
will need to be learnt.
Therefore, even myself still bad to write english, since my mind thinking
italian sentences.
 
J

Johannes Bauer

Carl said:
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
 
J

Johannes Bauer

George said:
The most obvious and readable of course: use two statements, as one
should do regardless of the language, instead of resorting to error-
prone hacks.

As I said in the reply to Carl, this might be okay for if-clauses, but
is bothering me with while-loops.

Regards,
Johannes
 
J

Johannes Bauer

TheSaint said:
If you want speak a language that isn't understood mostly you'll face
unexpected risults.
When you got started with C/C++, were you writing plain english to do
programs?
Far away to be a flame, each language have its own grammar that some time it
will need to be learnt.
Therefore, even myself still bad to write english, since my mind thinking
italian sentences.

Well, I do not really see your point - of couse I'm aware (and admitted)
that my Python skills are extremely amateurish. That's why I'm asking
for help here...

Regards,
Johannes
 
M

Marc 'BlackJack' Rintsch

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);
}

Can be written in Python as:

from functools import partial

# ...

for buf in iter(partial(f.read, buf_size), ''):
print '%s\n' % buf

Ciao,
Marc 'BlackJack' Rintsch
 
M

Marc 'BlackJack' Rintsch

As I said in the reply to Carl, this might be okay for if-clauses, but
is bothering me with while-loops.

Then try to write the ``while`` loop as ``for`` loop and move the
comparison into a generator function, or use the two argument variant of
`iter()`, or `itertools.takewhile()`.

Ciao,
Marc 'BlackJack' Rintsch
 
P

Paul McGuire

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);

}

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 <[email protected]>

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
 
W

William McBrine

char *tmp;
tmp = fgets(buf, sizeof(buf), f);
while (tmp) {
printf("%s\n", buf);
tmp = fgets(buf, sizeof(buf), f);
}

I think a more Pythonic way to write this, in general, would be:

while (1) {
char *tmp = fgets(buf, sizeof(buf), f);
if (!tmp)
break;
printf("%s\n", buf);
}

In actual Python, that's:

while True:
buf = f.readline()
if not buf:
break
print buf

Yeah, it's longer than the traditional C way, but you don't need to have
duplicate fgets() (or whatever) lines. On the plus side, you're less
likely to get '=' and '==' accidentally swapped in Python.

For this specific example, it can be cut down much more:

for buf in f.readlines():
print buf

(BTW, all of the above result in doublespacing the original file, but
that's what your C version was doing, so I kept it that way.)
 
C

Carl Banks

This is okay for if-clauses, but sucks for while-loops:

while (fgets(buf, sizeof(buf), f)) {
printf("%s\n", buf);

}


In earlier times, the Python idiom was this:

while True:
line = f.readline()
if not line:
break
print line

Not the prettiest thing ever, but it works fine, is readable, and
avoids a temporary variable. In C, given the choice between this or
using assignment expression, I'd say use either one. (But don't use
the version with a temporary, that's ugly as hell.)

More recent versions of Python have obviated the need to use this
idiom by making it possible to iterate over the lines of a file
directly. First they added xreadlines:

for line in xreadlines(f):
print line

Then they deprecated the xreadline function and made it a method:

for line in f.xreadlines():
print line

Then they recommended you no longer use that, and just made file
objects directly iterable:

for line in f:
print line

The point is, the Python language developers do share your concern
about these things. However, they still think assignment epxressions
are a very bad idea, so they've sought other solutions to these
issues.

(But, as I said, they have yet to provide an alternative for elif
clauses; you're stuck with workarounds there.)


Carl Banks
 
T

TheSaint

Well, I do not really see your point
You wrote C statements and I felt that you were trying to apply to python
interpreter.
I think that a minimun of knoweledge on python grammar it's the base for
doing some programming.
If your examples were there only to explain your meaning, then I'm wrong
here.
 
L

Lie

Hello group,

I'm just starting with Python and am extremely unexperienced with it so
far. Having a strong C/C++ background, I wish to do something like

if (q = getchar()) {
        printf("%d\n", q);

}

or translated to Python:

if (p = myfunction()):
        print p

However, this "assignment and comparison" is not working. What's the
"Python way" of doing this kind of thing?

Thanks a lot,
Johannes

Python often tries to avoid things it considers "bad design" in a
language, "assignment and comparison" is, for example, a bad design
because it is easily mistaken with "equality comparison", among other
things. This avoidance of bad design sometimes go as far as making
"the way" to do something in python completely different than doing
the same thing in other languages, thus it is always a good idea to
state what you intent in doing, rather than stating what you think you
need to do. An example is python's notion for 'for' loop, which can
only loop a list, most people coming from other languages would use
range/xrange here and there, a pythonic code would only rarely use a
range/xrange (usually in situations where the number of repetition is
constant).

Try reasking by stating what you wanted to do, rather than the
abstract question that states what you think you need to do you've
just asked. What functions you wanted to use and for what?
 
A

alex23

An example is python's notion for 'for' loop, which can
only loop a list[...]

Actually, the for statement steps through any object that provides an
iterator interface. Lists just happen to be one such object type.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top