[Tutor] streamlining a return statement
Erik Price
erikprice@mac.com
Mon, 9 Sep 2002 08:39:52 -0400
I have a function in a chunk of code that detects the presence of HTML
attributes in a string. If successful, the function returns a tuple
(containing 3 elements: the whitespace preceding the tag, the tag
element name itself, and a string containing all of the attributes of
the element).
It works fine. But I'm wondering whether returning an empty tuple is a
good idea. It feels like I should make use of Python's exception
facilities. (Right now the client code which uses this function works
by calling len() on the return value of the function, but I could
modify that to handle some kind of IndexError exception or whichever
exception is appropriate.)
Can someone criticize my code please? Specifically the "return"
statements -- the first part of the function is just the way I want it.
Also, using "if matchobj" works but is that the preferred way to
detect whether a re.search() was successful? (Testing for successful
assignment, "if matchobj = re.search()", which I admit is a Perlish way
of looking at it, doesn't work.)
def atts_detect(line):
"""searches a line for a tag with attributes and
returns a tuple of info about the tag if attributes are found"""
import re
# this regex ensures that the tag the kind we want
needle = r'(\s*)<(\w+)(\s+[-\w]+=[\'"].+[\'"])+(\s*/?>)'
regex = re.compile(needle)
# a match object is only returned if search is successful
matchobj = regex.search(line)
if matchobj: return matchobj.groups()
# return an empty tuple if no matches found
else: return ()
Thanks,
Erik
--
Erik Price
email: erikprice@mac.com
jabber: erikprice@jabber.org