Python quirk: Signatures are evaluated at import time

By Chris Lamb

Every Python programmer knows to avoid mutable default arguments:

def fn(mutable=[]):
    print mutable

$ python
['elem', 'elem']

However, many are not clear that this is due to arguments being evaluated at import time, rather than the first time the function is evaluated.

This results in related quirks such as:

def never_called(error=1/0):
$ python
Traceback (most recent call last):
  File "", line 1, in <module>
ZeroDivisionError: integer division or modulo by zero

... and an—implementation-specific—quirk caused by naive constant folding:

def never_called():
    99999999 ** 9999999
$ python

I suspect that this can be used as denial-of-service vector.

Chris Lamb is a freelance software developer and the current Debian Project Leader. You can read other posts by me, see software I have written or read more about me. You can also follow me @lolamby.

Planets: ALUG UWCS WUGLUG Debian

Thursday 21st July 2016