Ok. So. @pyexec
and @pyeval
work in a local scope, but this scope only exists while the code is being executed, it is not captured by any functions you define - this just seems to be how exec
works in python.
It’s not just imports that it affects, it’s all variables outside of the function scope. This includes the function itself so you can’t define recursive functions like this either.
One solution is to define the things you need to capture as globals. In your case you can put global np
at the top. This is probably what most people want to do.
Another solution (if you really need to avoid polluting global scope) is to put it all inside another function, which creates a new scope that can be captured, like:
@pyexec """
def makemysum():
import numpy as np
...
return mysum
mysum = makemysum()
"""
It’s not glamorous but it works.
Note: When I say “global scope”, I’m referring to a Python scope which is unique to whichever Julia module you are running in, so it’s not truly global. You don’t need to worry about code from outside your module interfering with Python’s global scope.