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 doSomething(x):
return numpy.sqrt(x)
Now to use that function in a separate module, I will import the name as
from lib import doSomething
...
Here is the tricky part... Now I want to expose another version of doSomething for which numpy has been imported from another library (in particular, from autograd). So, for instance, I would like to be able to have a function
from autograd import numpy
def doSomething(x):
return numpy.sqrt(x)
where the only difference between these functions is where numpy is being imported from. In particular, I would like to use both versions of doSomething in the same code, that is, I would like some way of importing doSomething twice... once with the default numpy, and once with the numpy from autograd. Something like this:
useAutograd = False
from lib(useAutograd) import doSomething
useAutograd = True
from lib(useAutograd) import doSomething as doSomethingAutograd
There are a couple options here that I know of, but none which are satisfactory.
I would make a copy of the codebase, and have one that uses the default
numpy, and one which usesnumpyfromautograd. This is bad because it would require me to maintain two codebases which are copies of each other, only with different imports.I could put in a conditional import:
try: from autograd import numpy except ImportError: import numpyThis is bad because the user has no control over which version is imported... If they have autograd, then they must use that version.
I could define an environmental variable to control the import
import os if os.environ.get('AUTOGRADNUMPY'): try: from autograd import numpy except ImportError: import numpy else: import numpyThis has the downside that although the user can control the import, they can only pick one version (as far as I know). So they could not use both versions in the same code.
Are there any better alternatives for this use case?
Background for those interested:
Autograd has its own set of functions which mimic numpy and allow one to easily compute derivatives using automatic differentation (in the same vein as tensorflow), without requiring expensive numerical differentiation.
HOWEVER, their numpy implementation is not the most optimized version (AFAIK). So it would be advantageous to allow the user to use the version with the autograd import when they will need the jacobian of the function, and to use their default, highly optimized numpy package when they don't.
doSomething, what's wrong with it? You won't import multiplenumpyasnumpyimported fromautogradis also pointed to which imported byimport numpy. They are the same.