Side-effects in python map (python “do” block)

前端 未结 2 746
借酒劲吻你
借酒劲吻你 2020-12-11 19:02

What is the preferred way to tell someone \"I want to apply func to each element in iterable for its side-effects.\"

# Option 1...          


        
相关标签:
2条回答
  • 2020-12-11 19:51

    Avoid the temptation to be clever. Use option 1, it's intent is clear and unambiguous; you are applying the function func() to each and every element in the iterable.

    Option 2 just confuses everyone, looking for what walk_for_side_effects is supposed to do (it certainly puzzled me until I realized you needed to iterate over map() in Python 3).

    Option 3 should be used when you actually get results from func(), never for the side effects. Smack anyone doing that just for the side-effects. List comprehensions should be used to generate a list, not to do something else. You are instead making it harder to comprehend and maintain your code (and building a list for all the return values is slower to boot).

    0 讨论(0)
  • 2020-12-11 19:54

    This has been asked many times, e.g., here and here. But it's an interesting question, though. List comprehensions are meant to be used for something else.

    Other options include

    1. use map() - basically the same as your sample
    2. use filter() - if your function returns None, you will get an empty list
    3. Just a plain for-loop

    while the plain loop is the preferable way to do it. It is semantically correct in this case, all other ways, including list comprehension, abuse concepts for their side-effect.

    In Python 3.x, map() and filter() are generators and thus do nothing until you iterate over them. So we'd need, e.g., a list(map(...)), which makes it even worse.

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