Sam-gege
Sam-gege

Reputation: 809

python import module with arguments

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

Upvotes: 0

Views: 426

Answers (1)

S4eed3sm
S4eed3sm

Reputation: 1478

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

Upvotes: 2

Related Questions