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
1 Answer 1
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
lang-py
if os.environ.get("CUDA") is not None: ...my_module.pycompute things in CPU or GPU. Is there a way?USE_GPU=true) rather than tied to the implementation (CUDA=true).