Danny W.
Danny W.

Reputation: 101

Python: calling external functions within functions

I am new to Python, and am having a problem: I want to write a function (Jacobian) which takes a function and a point as arguments, and returns the jacobian of that function at the given point.

Unsurprisingly, Jacobian relies on NumPy and SciPy. When I call Jacobian from another script, I get either:

  1. An error that says I cannot import a module into a function (when I have an import statement for NumPy/SciPy in Jacobian) or
  2. Errors that various NumPy/Scipy functions (e.g. zeros()) are not defined, (when I omit the import statement to avoid the error mentioned above.

What am I doing wrong?

Also, if someone knows of an implementation of Jacobian, that would be useful as well. There doesn't seem to be one in SciPy.

Upvotes: 0

Views: 648

Answers (1)

Duncan
Duncan

Reputation: 95772

You can import at the module level and then use the imported names from inside any functions. Or you can import any required names directly inside a function.

There is one situation where you cannot use import inside a function: you are not allowed to do from somemodule import * because the Python compiler wants to know all of the local variables in the function and with import * it cannot tell in advance what names will be imported.

The solution is simple: never use import *, always import exactly the names that you want to use.

P.S. It helps if you copy the code that is giving the problem and the exact error message you are getting. I'm guessing here that this is your problem but you'll get faster and more accurate answers if you provide the relevant details.

Upvotes: 2

Related Questions