I have a module lib
that needs numpy
. So, for instance, let\'s say I have a hypothetical function that looks like
import numpy
def doS
You don't need to do anything to achieve this.
If you do
from lib import doSomething
from lib_with_autograd import doSomething as doSomethingAutograd
each of those functions uses the numpy
imported in their specific module. So doSomethingAutograd
uses the one imported in lib_with_autograd
and doSomething
uses the one imported in lib
Since everything in python is an object, including modules, you can do something like:
def doSomething(x, numpy=None):
if numpy is None:
import numpy
return numpy.sqrt(x)
Then you can call the function without setting numpy
, then it will use the default numpy. If you want to use another numpy, just call it as such:
from autograd import numpy as autograd_numpy
doSomething(x, numpy=autograd_numpy)
If your desire is to avoid duplicating your code base, make your interface a class instead. For example:
class using_numpy:
import numpy
@classmethod
def do_something(cls, x):
return cls.numpy.sqrt(x)
class using_autograd(using_numpy):
from autograd import numpy
Now using_numpy.do_something
will use numpy
, and using_autograd.do_something
will use autograd.numpy
.
Alternatively, if you are uncomfortable with classmethod
, you could make your interfaces instances of a class, for example:
class interface:
def __init__(self, mdl):
self.mdl = mdl
def do_something(self, x):
return self.mdl.sqrt(x)
import numpy
import autograd
with_numpy = interface(numpy)
with_autograd = interface(autograd.numpy)