Tae Hyoun Park Tae Hyoun Park - 1 month ago 10
Python Question

Python Scipy accesses local variables in another function?

In Scipy, one-dimensional integration of a function with multiple parameters is achieved by specifying the constant parameters in the function definition through the


This example is from the Scipy Reference Guide:

>>> from scipy.integrate import quad
>>> def integrand(x, a, b):
... return a * x + b
>>> a = 2
>>> b = 1
>>> I = quad(integrand, 0, 1, args=(a,b))
>>> I = (2.0, 2.220446049250313e-14)


I always thought that local variables defined within functions are inaccessible outside the definition. Here, this seems not true since quad only requires
as the function argument, and it automatically knows that the variables used are
(x, a, b)
(and hence
(a, b)
are taken as parameters in the integration).

What is happening here? What am I missing?


quad doesn't know anything about what variables integrand uses. It doesn't know that the arguments are called a and b. It only sees the values of the global variables a and b, and it passes those values positionally to the integrand. In other words, the code would work the same if you did

x = 2
y = 1
I = quad(integrand, 0, 1, args=(x,y))

quad does not even know how many arguments integrand accepts, other than that it accepts at least one. quad passes the value of the variable of integration as the first argument. You, the user, have to know that, and pass the right number. If you don't (for instance if you didn't pass args, or just passed one arg), you'll get an error. quad just blindly passes along whatever arguments you give it.