0

I have a module that defines some functions, and I want this module to import different package based on arguments.

For example, I now have a file called my_module.py:

if CUDA is True:
    import numpy as pkg
else:
    import cupy as pkg

print(pkg.__name__)

When I import my_module from another file, I expect to somehow add an argument CUDA such than when it's True, then my_module imports cupy and then prints out "cupy", otherwise import numpy and prints "numpy"

For example, this is my main.py:

import my_module # somehow add an argument CUDA=False, should print "numpy"
>>> numpy
5
  • 2
    You can't pass arguments, the syntax simply doesn't support it: docs.python.org/3/reference/…. Typically this sort of thing is done by just trying to import the dependencies, and catching the error if they're not installed and falling back to the next one. Commented Dec 30, 2021 at 10:23
  • 3
    Consider using an environment variable? That's the right scope for what you're trying to do. if os.environ.get("CUDA") is not None: ... Commented Dec 30, 2021 at 10:28
  • Thanks for your answer. I have numpy and cupy installed, I simply want to choose whether my_module.py compute things in CPU or GPU. Is there a way? Commented Dec 30, 2021 at 10:28
  • As Adam suggests you could use an environment variable. I'd be inclined to make it semantic (USE_GPU=true) rather than tied to the implementation (CUDA=true). Commented Dec 30, 2021 at 10:29
  • Use a class. Instantiate the class with what u want Commented Dec 30, 2021 at 11:10

1 Answer 1

2

Maybe this works for you

main.py:

#main.py
import module

a = module.x()
b = module.x(True)
a.get_pkg()
b.get_pkg()

and

module.py:

class x:
    def __init__(self, numbers=False) -> None:
        if numbers:
            import numbers as pkg
            self.pkg = pkg
        else:
            import string as pkg
            self.pkg = pkg
    def get_pkg(self):
        print(self.pkg.__name__)

the putput of python main.py will be:

string
numbers
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.