Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the idiomatic way of invoking a list of functions in Python?

Tags:

python

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?
like image 843
ottodidakt Avatar asked Nov 29 '22 20:11

ottodidakt


2 Answers

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
like image 181
Stephan202 Avatar answered Dec 02 '22 10:12

Stephan202


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.

like image 21
quamrana Avatar answered Dec 02 '22 09:12

quamrana