473,394 Members | 1,916 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,394 software developers and data experts.

C-like assignment expression?

Hello,

I have an if-elif chain in which I'd like to match a string against
several regular expressions. Also I'd like to use the match groups
within the respective elif... block. The C-like idiom that I would
like to use is this:

if (match = my_re1.match(line):
# use match
elsif (match = my_re2.match(line)):
# use match
elsif (match = my_re3.match(line))
# use match

....buy this is illegal in python. The other way is to open up an else:
block in each level, do the assignment and then the test. This
unneccessarily leads to deeper and deeper nesting levels which I find
ugly. Just as ugly as first testing against the RE in the elif: clause
and then, if it matches, to re-evaluate the RE to access the match
groups.

Thanks,
robert
Jun 27 '08 #1
24 1599
bo*******@googlemail.com wrote:
Hello,

I have an if-elif chain in which I'd like to match a string against
several regular expressions. Also I'd like to use the match groups
within the respective elif... block. The C-like idiom that I would
like to use is this:

if (match = my_re1.match(line):
# use match
elsif (match = my_re2.match(line)):
# use match
elsif (match = my_re3.match(line))
# use match

...buy this is illegal in python. The other way is to open up an else:
block in each level, do the assignment and then the test. This
unneccessarily leads to deeper and deeper nesting levels which I find
ugly. Just as ugly as first testing against the RE in the elif: clause
and then, if it matches, to re-evaluate the RE to access the match
groups.
This might help:

-----------
s = "foo"

class Tester(object):

def __call__(self, pattern):
self.m = re.match(pattern, s)
return self.m is not None

def __getattr__(self, name):
return getattr(self.m, name)

test = Tester()

if test("bar"):
print "wrong"
elif test("foo"):
print "right"
-------------
Diez
Jun 27 '08 #2
bo*******@googlemail.com wrote:
I have an if-elif chain in which I'd like to match a string against
several regular expressions. Also I'd like to use the match groups
within the respective elif... block. The C-like idiom that I would
like to use is this:

if (match = my_re1.match(line):
# use match
elsif (match = my_re2.match(line)):
# use match
elsif (match = my_re3.match(line))
# use match

...buy this is illegal in python. The other way is to open up an else:
block in each level, do the assignment and then the test. This
unneccessarily leads to deeper and deeper nesting levels which I find
ugly.
How about this (untested) code:

for re in (re1, re2, re3):
match = re.match(line)
if match:
# use it

This requires that "use it" means the same for each regular expression
though...

Uli

--
Sator Laser GmbH
Geschäftsführer: Thorsten Föcking, Amtsgericht Hamburg HR B62 932

Jun 27 '08 #3
bo*******@googlemail.com a écrit :
Hello,

I have an if-elif chain in which I'd like to match a string against
several regular expressions. Also I'd like to use the match groups
within the respective elif... block. The C-like idiom that I would
like to use is this:

if (match = my_re1.match(line):
# use match
elsif (match = my_re2.match(line)):
# use match
elsif (match = my_re3.match(line))
# use match
<ot>
Isn't it the third or fourth time this very same question pops up here ?
Starts to look like a FAQ.
</ot>

The canonical solution is to iterate over a list of expression,function
pairs, ie:

def use_match1(match):
# code here

def use_match2(match):
# code here

def use_match3(match):
# code here

for exp, func in [
(my_re1, use_match1),
(my_re2, use_match2),
(my_re3, use_match3)
]:
match = exp.match(line)
if match:
func(match)
break
The alternate solution is Diez's Test object.

HTH
Jun 27 '08 #4
Bruno Desthuilliers <br********************@websiteburo.invalid>
writes:
The canonical solution is to iterate over a list of
expression,function pairs, ie:
Although that solution is pretty, it is not the canonical solution
because it doesn't cover the important case of "if" bodies needing to
access common variables in the enclosing scope. (This will be easier
in Python 3 with 'nonlocal', though.) The snippet posted by Diez is
IMHO closer to a canonical solution to this FAQ.
Jun 27 '08 #5
On May 21, 1:47 pm, Hrvoje Niksic <hnik...@xemacs.orgwrote:
Although that solution is pretty, it is not the canonical solution
because it doesn't cover the important case of "if" bodies needing to
access common variables in the enclosing scope. (This will be easier
in Python 3 with 'nonlocal', though.) The snippet posted by Diez is
IMHO closer to a canonical solution to this FAQ.
Hello everybody,

thanks for the various answers. I'm actually pretty puzzled because I
expected to see some obvious solution that I just hadn't found before.
In general I find Python more elegant and syntactically richer than C
(that's where I come from), so I didn't expect the solutions to be a
lot more verbose and/or ugly (no offense) than the original idea which
would have worked if Python's assignment statement would double as
expression, as in C.

Thanks again,
robert

PS: Since I'm testing only three REs, and I only need the match
results from one of them, I just re-evaluate that one.
Jun 27 '08 #6
On May 21, 3:12 pm, "boblat...@googlemail.com"
<boblat...@googlemail.comwrote:
On May 21, 1:47 pm, Hrvoje Niksic <hnik...@xemacs.orgwrote:
Although that solution is pretty, it is not the canonical solution
because it doesn't cover the important case of "if" bodies needing to
access common variables in the enclosing scope. (This will be easier
in Python 3 with 'nonlocal', though.) The snippet posted by Diez is
IMHO closer to a canonical solution to this FAQ.

Hello everybody,

thanks for the various answers. I'm actually pretty puzzled because I
expected to see some obvious solution that I just hadn't found before.
In general I find Python more elegant and syntactically richer than C
(that's where I come from), so I didn't expect the solutions to be a
lot more verbose and/or ugly (no offense) than the original idea which
would have worked if Python's assignment statement would double as
expression, as in C.

Thanks again,
robert

PS: Since I'm testing only three REs, and I only need the match
results from one of them, I just re-evaluate that one.
Is it really a lot to change to have it

if my_re1.match(line):
match = my_re1.match(line)
elseif my_re2.match(line):
match = my_re2.match(line)
elseif my_re3.match(line):
match = my_re3.match(line)

?

That reads clearly to me...
Jun 27 '08 #7
bo*******@googlemail.com wrote:
On May 21, 1:47 pm, Hrvoje Niksic <hnik...@xemacs.orgwrote:
>Although that solution is pretty, it is not the canonical solution
because it doesn't cover the important case of "if" bodies needing to
access common variables in the enclosing scope. (This will be easier
in Python 3 with 'nonlocal', though.) The snippet posted by Diez is
IMHO closer to a canonical solution to this FAQ.

Hello everybody,

thanks for the various answers. I'm actually pretty puzzled because I
expected to see some obvious solution that I just hadn't found before.
In general I find Python more elegant and syntactically richer than C
(that's where I come from), so I didn't expect the solutions to be a
lot more verbose and/or ugly (no offense) than the original idea which
would have worked if Python's assignment statement would double as
expression, as in C.
Well, it's a design-decision - and I'm pretty ok with it being a bit verbose
here - as it prevents a *great* deal of programming errors that would
otherwise happen from accidentally writing a = b where a == b was meant.

One could argue that regular expressions - which seem to be THE case where
it bugs people - should offer a standard way that essentially works as my
solution - by keeping state around, making series of tests easier.
Diez
Jun 27 '08 #8
co*********@gmail.com wrote:
On May 21, 3:12 pm, "boblat...@googlemail.com"
<boblat...@googlemail.comwrote:
>On May 21, 1:47 pm, Hrvoje Niksic <hnik...@xemacs.orgwrote:
Although that solution is pretty, it is not the canonical solution
because it doesn't cover the important case of "if" bodies needing to
access common variables in the enclosing scope. (This will be easier
in Python 3 with 'nonlocal', though.) The snippet posted by Diez is
IMHO closer to a canonical solution to this FAQ.

Hello everybody,

thanks for the various answers. I'm actually pretty puzzled because I
expected to see some obvious solution that I just hadn't found before.
In general I find Python more elegant and syntactically richer than C
(that's where I come from), so I didn't expect the solutions to be a
lot more verbose and/or ugly (no offense) than the original idea which
would have worked if Python's assignment statement would double as
expression, as in C.

Thanks again,
robert

PS: Since I'm testing only three REs, and I only need the match
results from one of them, I just re-evaluate that one.

Is it really a lot to change to have it

if my_re1.match(line):
match = my_re1.match(line)
elseif my_re2.match(line):
match = my_re2.match(line)
elseif my_re3.match(line):
match = my_re3.match(line)

?

That reads clearly to me...
And wastes time. regular expressions can become expensive to match - doing
it twice might be hurtful.

Diez
Jun 27 '08 #9
>
And wastes time. regular expressions can become expensive to match - doing
it twice might be hurtful.

Diez
match = (my_re1.match(line) or my_re2.match(line)) or
my_re3.match(line)

?
Jun 27 '08 #10
co*********@gmail.com wrote:
>>
And wastes time. regular expressions can become expensive to match -
doing it twice might be hurtful.

Diez

match = (my_re1.match(line) or my_re2.match(line)) or
my_re3.match(line)
How do you know *which* of the three has matched then?

Diez
Jun 27 '08 #11
On May 21, 4:09 pm, "Diez B. Roggisch" <de...@nospam.web.dewrote:
cokofree...@gmail.com wrote:
And wastes time. regular expressions can become expensive to match -
doing it twice might be hurtful.
Diez
match = (my_re1.match(line) or my_re2.match(line)) or
my_re3.match(line)

How do you know *which* of the three has matched then?

Diez
Depends if the OP wants to know that...
Jun 27 '08 #12
one of the few things i miss from C is being able to use assignment in
expressions. that's the only thing, really.
also there's no switch/case, you have to use a dictionary of functions
instead, although i rarely need that, usually i just use elif.

<bo*******@googlemail.comwrote in message
news:7d**********************************@26g2000h sk.googlegroups.com...
On May 21, 1:47 pm, Hrvoje Niksic <hnik...@xemacs.orgwrote:
>Although that solution is pretty, it is not the canonical solution
because it doesn't cover the important case of "if" bodies needing to
access common variables in the enclosing scope. (This will be easier
in Python 3 with 'nonlocal', though.) The snippet posted by Diez is
IMHO closer to a canonical solution to this FAQ.

Hello everybody,

thanks for the various answers. I'm actually pretty puzzled because I
expected to see some obvious solution that I just hadn't found before.
In general I find Python more elegant and syntactically richer than C
(that's where I come from), so I didn't expect the solutions to be a
lot more verbose and/or ugly (no offense) than the original idea which
would have worked if Python's assignment statement would double as
expression, as in C.

Thanks again,
robert

PS: Since I'm testing only three REs, and I only need the match
results from one of them, I just re-evaluate that one.

Jun 27 '08 #13
co*********@gmail.com wrote:
On May 21, 4:09 pm, "Diez B. Roggisch" <de...@nospam.web.dewrote:
>cokofree...@gmail.com wrote:
>And wastes time. regular expressions can become expensive to match -
doing it twice might be hurtful.
>Diez
match = (my_re1.match(line) or my_re2.match(line)) or
my_re3.match(line)

How do you know *which* of the three has matched then?

Diez

Depends if the OP wants to know that...
Well, in *general* one wants that. So as a general-purpose solution this is
certainly *not* the way to go.

Diez
Jun 27 '08 #14
On May 21, 4:57 pm, "inhahe" <inh...@gmail.comwrote:
one of the few things i miss from C is being able to use assignment in
expressions. that's the only thing, really.
also there's no switch/case, you have to use a dictionary of functions
instead, although i rarely need that, usually i just use elif.
One thing I hate from C is the assignment in expressions...Forcing
myself to write
0 == Something
rather than
Something == 0
just to make sure I was mistakenly assigning values in statements is
annoying, it ruins the ease of reading.

I kind of agree with the select:case, but I think a key issue is how
to implement it. Elif is reasonable for now.

Diez, true I guess, but then we haven't seen what these expressions
are, and why there has to be three.
Jun 27 '08 #15
On 21 Mai, 11:38, boblat...@googlemail.com wrote:
Hello,

I have an if-elif chain in which I'd like to match a string against
several regular expressions. Also I'd like to use the match groups
within the respective elif... block. The C-like idiom that I would
like to use is this:

if (match = my_re1.match(line):
# use match
elsif (match = my_re2.match(line)):
# use match
elsif (match = my_re3.match(line))
# use match

...buy this is illegal in python. The other way is to open up an else:
block in each level, do the assignment and then the test. This
unneccessarily leads to deeper and deeper nesting levels which I find
ugly. Just as ugly as first testing against the RE in the elif: clause
and then, if it matches, to re-evaluate the RE to access the match
groups.

Thanks,
robert
You are perfectly correct. Pythons design is lacking here IMO. But
what is your question?
Jun 27 '08 #16

<co*********@gmail.comwrote in message
news:06**********************************@p25g2000 hsf.googlegroups.com...
On May 21, 4:57 pm, "inhahe" <inh...@gmail.comwrote:
>one of the few things i miss from C is being able to use assignment in
expressions. that's the only thing, really.
also there's no switch/case, you have to use a dictionary of functions
instead, although i rarely need that, usually i just use elif.

One thing I hate from C is the assignment in expressions...Forcing
myself to write
0 == Something
rather than
Something == 0
interesting trick, i've never thought of that/seen it
although if Python implemented it I think it should default to giving
warnings when you use = in an expression, that way you don't have to worry.
just to make sure I was mistakenly assigning values in statements is
annoying, it ruins the ease of reading.

I kind of agree with the select:case, but I think a key issue is how
to implement it. Elif is reasonable for now.

Diez, true I guess, but then we haven't seen what these expressions
are, and why there has to be three.

Jun 27 '08 #17
>>
>One thing I hate from C is the assignment in expressions...Forcing
myself to write
0 == Something
rather than
Something == 0

interesting trick, i've never thought of that/seen it
although if Python implemented it I think it should default to giving
warnings when you use = in an expression, that way you don't have to
worry.
That introduces complications though, do you want to see a pagefull of
warnings every time you import a module that uses the ='s?
You could specify in your python file that you want to suppress that
warning, but then you'd never know when you used = by accident when you
meant to use ==.
anyway i was thinking you could have a second assignment operator to use
just in expressions, and only allow that. it could be := since some
languages tend to use that. i wouldn't like it as a general assignment
operator but assignment in expressions is a special case. also <- or ->.
C uses -for functions but I think math/calculators use that for
assignment.


Jun 27 '08 #18
On May 21, 5:50 pm, "inhahe" <inh...@gmail.comwrote:
One thing I hate from C is the assignment in expressions...Forcing
myself to write
0 == Something
rather than
Something == 0
interesting trick, i've never thought of that/seen it
although if Python implemented it I think it should default to giving
warnings when you use = in an expression, that way you don't have to
worry.

That introduces complications though, do you want to see a pagefull of
warnings every time you import a module that uses the ='s?
You could specify in your python file that you want to suppress that
warning, but then you'd never know when you used = by accident when you
meant to use ==.
anyway i was thinking you could have a second assignment operator to use
just in expressions, and only allow that. it could be := since some
languages tend to use that. i wouldn't like it as a general assignment
operator but assignment in expressions is a special case. also <- or ->.
C uses -for functions but I think math/calculators use that for
assignment.
My preference would be ?=.

if match ?= my_re1.match(line):
# use match
elif match ?= my_re2.match(line):
# use match
elif match ?= my_re3.match(line):
# use match
Jun 27 '08 #19
On May 21, 11:38 am, boblat...@googlemail.com wrote:
if (match = my_re1.match(line):
# use match
elsif (match = my_re2.match(line)):
# use match
elsif (match = my_re3.match(line))
# use match

...buy this is illegal in python.

Assignment expressions is disallowed in Python to protect against a
very common bug in C/C++ programs, the (accidental) confusion of

if (match = my_re1.match(line))

with

if (match == my_re1.match(line))

or vice versa.


Jun 27 '08 #20
On May 21, 10:38 am, boblat...@googlemail.com wrote:
Hello,

I have an if-elif chain in which I'd like to match a string against
several regular expressions. Also I'd like to use the match groups
within the respective elif... block. The C-like idiom that I would
like to use is this:

if (match = my_re1.match(line):
# use match
elsif (match = my_re2.match(line)):
# use match
elsif (match = my_re3.match(line))
# use match

...buy this is illegal in python. The other way is to open up an else:
block in each level, do the assignment and then the test. This
unneccessarily leads to deeper and deeper nesting levels which I find
ugly. Just as ugly as first testing against the RE in the elif: clause
and then, if it matches, to re-evaluate the RE to access the match
groups.

Thanks,
robert
You could use named groups to search for all three patterns at once
like this:
original:

prog1 = re.compile(r'pat1')
prog2 = re.compile(r'pat2')
prog3 = re.compile(r'pat3')
...

Becomes:

prog = re.compile(r'(?P<p1>pat1)|(?P<p2>pat2)|(?P<p3>pat3 )')
match = prog.match(line)
for p in 'p1 p2 p3'.split():
if match.groupdict()[p]:
do_something_for_prog(p)
- Paddy.

Jun 27 '08 #21
On 21 Mai, 19:56, sturlamolden <sturlamol...@yahoo.nowrote:
On May 21, 11:38 am, boblat...@googlemail.com wrote:
if (match = my_re1.match(line):
# use match
elsif (match = my_re2.match(line)):
# use match
elsif (match = my_re3.match(line))
# use match
...buy this is illegal in python.

Assignment expressions is disallowed in Python to protect against a
very common bug in C/C++ programs, the (accidental) confusion of

if (match = my_re1.match(line))

with

if (match == my_re1.match(line))

or vice versa.
This is just a syntactical issue. But what is the *value* of an
assigment? In Python it is always None: assigments are statements, not
expressions.

However Guido and team have found a *pragmatic* solution for this at
another place:

with open("myFile") as f:
BLOCK

Compare this with a possible syntactical form of an if-statement:

if EXPR as NAME:
BLOCK

This isn't ugly syntax-wise. It's just a bit harder to understand the
semantics of an if-statement. It might read like this:

"Evaluate EXPR and compute bool(EXPR). If this value is True assign
EXPR to NAME and execute BLOCK. Otherwise refuse both assigment and
BLOCK execution."

Maybe assignment can be performed unconditionally as in the C case.
I'm not sure about this.
Jun 27 '08 #22
On 2008-05-21, Diez B. Roggisch <de***@nospam.web.dewrote:
bo*******@googlemail.com wrote:
>On May 21, 1:47 pm, Hrvoje Niksic <hnik...@xemacs.orgwrote:
>>Although that solution is pretty, it is not the canonical solution
because it doesn't cover the important case of "if" bodies needing to
access common variables in the enclosing scope. (This will be easier
in Python 3 with 'nonlocal', though.) The snippet posted by Diez is
IMHO closer to a canonical solution to this FAQ.

Hello everybody,

thanks for the various answers. I'm actually pretty puzzled because I
expected to see some obvious solution that I just hadn't found before.
In general I find Python more elegant and syntactically richer than C
(that's where I come from), so I didn't expect the solutions to be a
lot more verbose and/or ugly (no offense) than the original idea which
would have worked if Python's assignment statement would double as
expression, as in C.

Well, it's a design-decision - and I'm pretty ok with it being a bit verbose
here - as it prevents a *great* deal of programming errors that would
otherwise happen from accidentally writing a = b where a == b was meant.
But that is an error that occurs because of the specific symbols chosen
to represent an assignment or equality test. At the time python was
first designed, other symbols for assignment were already used for
in other languages, like := and <-

So if preventing errors was the main motivation why not allow an
assignment to be an expression but use a symbol for the assignment
that would prevent those kind of errors?

I find it hard to believe that a design choice like whether or not
to have the assignment behave as an expression or not, was decided
on the ground of a particulare lexical representation of the assignment
symbol.

--
Antoon Pardon
Jun 27 '08 #23
On May 21, 4:38*am, boblat...@googlemail.com wrote:
Hello,

I have an if-elif chain in which I'd like to match a string against
several regular expressions. Also I'd like to use the match groups
within the respective elif... block. The C-like idiom that I would
like to use is this:

if (match = my_re1.match(line):
* # use match
elsif (match = my_re2.match(line)):
* # use match
elsif (match = my_re3.match(line))
* # use match

...buy this is illegal in python. The other way is to open up an else:
block in each level, do the assignment and then the test. This
unneccessarily leads to deeper and deeper nesting levels which I find
ugly. Just as ugly as first testing against the RE in the elif: clause
and then, if it matches, to re-evaluate the RE to access the match
groups.

Thanks,
robert
Try this.

-- Paul

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 bool(self.value)
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
Jun 27 '08 #24
This version is a bit better, since it follows the convention that
'<<' should return self.

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__

-- Paul
Jun 27 '08 #25

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

23
by: Paul Rubin | last post by:
OK, I want to scan a file for lines matching a certain regexp. I'd like to use an assignment expression, like for line in file: if (g := re.match(pat, line)): croggle(g.group(1)) Since...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.