I have a list of callback functions that I need to invoke when an event is fired. Is this idiomatic python?
def first_callback(m):
print 'first ' + m
def second_callback(m):
print 'second ' + m
lst = [first_callback, second_callback]
map(lambda x: x("event_info"),lst) #is this how you do it?
Use map
only for functions without side effects (like print
). That is, use it only for functions that just return something. In this case a regular loop is more idiomatic:
for f in lst:
f("event_info")
Edit: also, as of Python 3.0, map
returns an iterator instead of a list. Hence in Python 3.0 the code given in the question will not call any function, unless all elements in the generator are evaluated explicitly (e.g. by encapsulating the call to map
inside list
). Luckily the 2to3 tool will warn about this:
File map.py
:
map(lambda x: x, range(10))
2to3-3.0 map.py
output:
RefactoringTool: Skipping implicit fixer: buffer
RefactoringTool: Skipping implicit fixer: idioms
RefactoringTool: Skipping implicit fixer: set_literal
RefactoringTool: Skipping implicit fixer: ws_comma
--- map.py (original)
+++ map.py (refactored)
@@ -1,1 +1,1 @@
-map(lambda x: x, range(10))
+list(map(lambda x: x, list(range(10))))
RefactoringTool: Files that need to be modified:
RefactoringTool: map.py
RefactoringTool: Warnings/messages while refactoring:
RefactoringTool: ### In file map.py ###
RefactoringTool: Line 1: You should use a for loop here
You could also write a list comprehension:
[f("event_info") for f in lst]
However, it does have the side-effect of returning a list of results.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With