numba/numba

Dangerous default arguments in numba

Open

#5,809 opened on Jun 3, 2020

View on GitHub
 (4 comments) (0 reactions) (0 assignees)Python (1,132 forks)batch import
buggood first issue

Repository metrics

Stars
 (9,177 stars)
PR merge metrics
 (Avg merge 14d 16h) (30 merged PRs in 30d)

Description

While reading the numba source code I noticed that dangerous default arguments are used in several places.

When defining a function like

def f(arg={}):
    pass

the default argument is created during the definition of the function, not during the call.

That means that all calls which fall to the default argument share the same instance of that dictionary (list, etc..)

This can easily have "funny" side effects, as shown in the following (somewhat contrived) example

from numba import njit, int32

@njit
def f(x):
    c = 0.5
    return c+x
print(f(1))

f.locals["c"] = int32

@njit
def g(x):
    c = 0.5
    return c+x
print(g(1))
print(g.locals)

returns

1.5
1
{'c': int32}

This happens because f and g end up sharing the same instance of locals (the jit decorator is defined as def jit([...], locals={})).

Contributor guide