Return value of an assignment statement?

Jeff Schwab jeff at schwabcenter.com
Thu Feb 21 17:17:43 EST 2008


mrstephengross wrote:
>> What you can't do (that I really miss) is have a tree of assign-and-test
>> expressions:
>>         import re
>>         pat = re.compile('some pattern')
>>         if m = pat.match(some_string):
>>             do_something(m)
> 
> Yep, this is exactly what I am (was) trying to do. Oh well.... Any
> clever ideas on this front?

I worked around it by defining a separate thigamabob with a "result" 
property.  A method of the thigamabob internally performs the 
assignment, and returns a boolean result.  The body of each branch in 
the tree can then retrieve the result object from the thigamabob. 
Here's an example hard-coded to match strings against patterns, but I 
think the idea should be extensible to other kinds of assign-and-test 
situations.

     # Just for the sake of this post.
     def do_something(m): pass
     def do_other_thing(m): pass
     def do_default_thing(): pass

     import re

     class Matcher(object):
         def __call__(self, pattern, string):
             self.result = pattern.match(string)

     if __name__ == '__main__':

         pat = re.compile('some pattern')
         match = Matcher()

         if match(pat, 'a'):
             do_something(match.result)
         elif match(pat, 'b'):
             do_other_thing(match.result)
         else:
             do_default_thing()



More information about the Python-list mailing list