pythonic way to rewrite an assignment in an if statement

前端 未结 7 818
隐瞒了意图╮
隐瞒了意图╮ 2020-12-19 10:37

Is there a pythonic preferred way to do this that I would do in C++:


for s in str:
    if r = regex.match(s):
        print r.groups()

I r

7条回答
  •  攒了一身酷
    2020-12-19 11:06

    Yet another answer is to use the "Assign and test" recipe for allowing assigning and testing in a single statement published in O'Reilly Media's July 2002 1st edition of the Python Cookbook and also online at Activestate. It's object-oriented, the crux of which is this:

    # from http://code.activestate.com/recipes/66061
    class DataHolder:
        def __init__(self, value=None):
            self.value = value
        def set(self, value):
            self.value = value
            return value
        def get(self):
            return self.value
    

    This can optionally be modified slightly by adding the custom __call__() method shown below to provide an alternative way to retrieve instances' values -- which, while less explicit, seems like a completely logical thing for a 'DataHolder' object to do when called, I think.

        def __call__(self):
            return self.value
    

    Allowing your example to be re-written:

    r = DataHolder()
    for s in strings:
        if r.set(regex.match(s))
            print r.get().groups()
    # or
            print r().groups()
    

    As also noted in the original recipe, if you use it a lot, adding the class and/or an instance of it to the __builtin__ module to make it globally available is very tempting despite the potential downsides:

    import __builtin__
    __builtin__.DataHolder = DataHolder
    __builtin__.data = DataHolder()
    

    As I mentioned in my other answer to this question, it must be noted that this approach is limited to holding only one result/value at a time, so more than one instance is required to handle situations where multiple values need to be saved simultaneously, such as in nested function calls, loops or other threads. That doesn't mean you should use it or the other answer, just that more effort will be required.

提交回复
热议问题