Python IF statements and assignments

Status
Not open for further replies.
I have a simple question that I can workaround, but I'd like to find the Pythonic way of doing it.

I'm using Python 3.1.2.

Code:
xml = open('apps.xml', 'r')
for line in xml:
if re.match("<Application id=.*", line):

re.match() will return a match object if the regex is found and None if not. Basically, I need to do some stuff with the match object inside the "if" statement. I need to do several operations, but most of them revolve around using the returned match object.
I'd like to do the following, but Python doesn't accept the syntax.
Code:
if tmp = re.match("<Application id=.*", line):
Where I assign the match object to tmp, not testing for equality.

From my understanding, Python removed this functionality because it causes so many programming errors. What is the Pythonic way to do this?
 

bk0

Ars Tribunus Militum
1,801
Is there some reason you don't like the following:
Code:
xml = open('apps.xml', 'r')
for line in xml:
matchobj = re.match("<Application id=.*", line):
if matchobj:
    #do something
else:
    #do something else

(http://docs.python.org/py3k/library/re.html)
Match Objects always have a boolean value of True, so that you can test whether e.g. match() resulted in a match with a simple if statement. They support the following methods and attributes...

Though I'm not sure you want to go messing w/ XML via regexps unless you really need to (use ElementTree instead).
 
I'm validating my XML parser, which uses lxml.etree. My parser isn't finding enough objects, so I'm just going through the file to see what's missing.

I tried to post an update to my earlier post, but it was eaten.

It turns out that I don't need anything from the match object. I can simply split my loop variable, "line." So I just do the following:
Code:
for line in xml:
    if re.search("<Application id=.+", line[:-1]):
        xmllist.append(line[:-1].split("=")[1])
        ...
 
Status
Not open for further replies.