1

Question

For a possibly convoluted reason (see below), I want to do something like the following:

def import_np():
    import numpy
    return numpy.array([0])

def test_np():
    return numpy.array([1])

Now if I try calling these two methods, the first works but the second doesn't: it says numpy is not defined. How can I fix this?

Background

I would like to import an in-house module of which we have many versions (edit: to clarify, we branch for every release). Ideally, I'd like to parametrise the import statement, but I can't do that, so I thought I could have a function that looks like this:

def import_version(path_to_version):
    sys.path.append(path_to_version)
    import the_module

However, I can't use the_module outside of this method, which has led to my question above.

butterflyknife
  • 1,438
  • 8
  • 17
  • 2
    Okay, but having multiple versions of the same module floating around is really the basis for your problem. You should review the code of that module and find ways to unify those multiple version, or you should write a wrapper that bridges the differences. What you are trying to do will tie you down to a hacky, broken structure... so if more code is built on top of that, it won't be pretty. – logicOnAbstractions Nov 24 '20 at 13:26
  • @logicOnAbstractions -- it's just what we do: we branch for every release. I can't change it. – butterflyknife Nov 24 '20 at 13:31
  • 1
    Take a look at [`importlib.import_module`](https://docs.python.org/3/library/importlib.html#importlib.import_module) – jkr Nov 24 '20 at 13:38

1 Answers1

1

You can use the path to your package version as a configuration variable that will be global to your script. Then you can do the sys.path.append function call using that global variable and the import scope is the whole script in which you are importing the module.

I would recommend you to catch exceptions when the module load fails.

import config
MODULE_PATH = config.path_to_version
sys.path.append(MODULE_PATH)
try:
   import the_module
except Exception as exp:
   // exception logging

Here you have a file config.py containing the path to the module version

path_to_version="your-path"
saloua
  • 2,433
  • 4
  • 27
  • 37