Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: default argument values vs global variables

I saw this default values usage in the Python's Queue module:

def _put(self, item, heappush=heapq.heappush):
    heappush(self.queue, item)

def _get(self, heappop=heapq.heappop):
    return heappop(self.queue)

I wonder why the variables are used as function arguments here? Is it just a matter of taste or some kind of optimization?

like image 638
Eugene Yarmash Avatar asked Feb 03 '26 07:02

Eugene Yarmash


1 Answers

It's a micro optimization. Default values are evaluated only once at function definition time, and locals (including parameters) are a bit faster to access than globals, they're implemented as a C array lookup instead of a dict lookup. It also allows avoiding repeatedly looking up the heappush and heappop members of heapq, without polluting the namespace by pulling them in directly.

Timeit snippets:

python -mtimeit --setup "import heapq" --setup "def f(q,x,p=heapq.heappush): p(q,x)" "f([], 1)"
1000000 loops, best of 3: 0.538 usec per loop

python -mtimeit --setup "import heapq" --setup "def f(q,p=heapq.heappop): p(q)" "f([1])"
1000000 loops, best of 3: 0.386 usec per loop

python -mtimeit --setup "import heapq" --setup "def f(q,x): heapq.heappush(q,x)" "f([], 1)"
1000000 loops, best of 3: 0.631 usec per loop

python -mtimeit --setup "import heapq" --setup "def f(q): heapq.heappop(q)" "f([1])"
1000000 loops, best of 3: 0.52 usec per loop

Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!