473,807 Members | 2,883 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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(li ne):
# use match
elsif (match = my_re2.match(li ne)):
# use match
elsif (match = my_re3.match(li ne))
# 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 1641
bo*******@googl email.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(li ne):
# use match
elsif (match = my_re2.match(li ne)):
# use match
elsif (match = my_re3.match(li ne))
# 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(patter n, s)
return self.m is not None

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

test = Tester()

if test("bar"):
print "wrong"
elif test("foo"):
print "right"
-------------
Diez
Jun 27 '08 #2
bo*******@googl email.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(li ne):
# use match
elsif (match = my_re2.match(li ne)):
# use match
elsif (match = my_re3.match(li ne))
# 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ühr er: Thorsten Föcking, Amtsgericht Hamburg HR B62 932

Jun 27 '08 #3
bo*******@googl email.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(li ne):
# use match
elsif (match = my_re2.match(li ne)):
# use match
elsif (match = my_re3.match(li ne))
# 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,func tion
pairs, ie:

def use_match1(matc h):
# code here

def use_match2(matc h):
# code here

def use_match3(matc h):
# 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************ ********@websit eburo.invalid>
writes:
The canonical solution is to iterate over a list of
expression,func tion 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...@goog lemail.com"
<boblat...@goog lemail.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(li ne):
match = my_re1.match(li ne)
elseif my_re2.match(li ne):
match = my_re2.match(li ne)
elseif my_re3.match(li ne):
match = my_re3.match(li ne)

?

That reads clearly to me...
Jun 27 '08 #7
bo*******@googl email.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*********@gma il.com wrote:
On May 21, 3:12 pm, "boblat...@goog lemail.com"
<boblat...@goog lemail.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(li ne):
match = my_re1.match(li ne)
elseif my_re2.match(li ne):
match = my_re2.match(li ne)
elseif my_re3.match(li ne):
match = my_re3.match(li ne)

?

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(l ine) or my_re2.match(li ne)) or
my_re3.match(li ne)

?
Jun 27 '08 #10

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

Similar topics

23
3241
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 there are no assignment expressions in Python, I have to use a temp var. That's a little more messy, but bearable:
0
9720
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
1
10374
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10112
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9193
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7650
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5685
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4330
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3854
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3011
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.