Is it Pythonic to use list comprehensions for just side effects?

后端 未结 7 693
面向向阳花
面向向阳花 2020-11-21 06:23

Think about a function that I\'m calling for its side effects, not return values (like printing to screen, updating GUI, printing to a file, etc.).

def fun_wi         


        
相关标签:
7条回答
  • 2020-11-21 06:49

    Second is better.

    Think of the person who would need to understand your code. You can get bad karma easily with the first :)

    You could go middle between the two by using filter(). Consider the example:

    y=[1,2,3,4,5,6]
    def func(x):
        print "call with %r"%x
    
    for x in filter(lambda x: x>3, y):
        func(x)
    
    0 讨论(0)
  • 2020-11-21 06:53

    List comprehensions are for creating lists. And unless you are actually creating a list, you should not use list comprehensions.

    So I would got for the second option, just iterating over the list and then call the function when the conditions apply.

    0 讨论(0)
  • 2020-11-21 06:54

    It is very anti-Pythonic to do so, and any seasoned Pythonista will give you hell over it. The intermediate list is thrown away after it is created, and it could potentially be very, very large, and therefore expensive to create.

    0 讨论(0)
  • 2020-11-21 06:56

    You shouldn't use a list comprehension, because as people have said that will build a large temporary list that you don't need. The following two methods are equivalent:

    consume(side_effects(x) for x in xs)
    
    for x in xs:
        side_effects(x)
    

    with the definition of consume from the itertools man page:

    def consume(iterator, n=None):
        "Advance the iterator n-steps ahead. If n is none, consume entirely."
        # Use functions that consume iterators at C speed.
        if n is None:
            # feed the entire iterator into a zero-length deque
            collections.deque(iterator, maxlen=0)
        else:
            # advance to the empty slice starting at position n
            next(islice(iterator, n, n), None)
    

    Of course, the latter is clearer and easier to understand.

    0 讨论(0)
  • 2020-11-21 07:06

    Depends on your goal.

    If you are trying to do some operation on each object in a list, the second approach should be adopted.

    If you are trying to generate a list from another list, you may use list comprehension.

    Explicit is better than implicit. Simple is better than complex. (Python Zen)

    0 讨论(0)
  • 2020-11-21 07:12

    You can do

    for z in (fun_with_side_effects(x) for x in y if (...conditions...)): pass
    

    but it's not very pretty.

    0 讨论(0)
提交回复
热议问题