I'm making a Python package, inside a module, I have several python classes, but only one of them uses a specific package (tensorflow), which is installed using the extras_require
option in setup.py
file, since it's a heavy dependency and it's used in a very small part of the project.
Let's say I have the class MyClassRegular, and MyClassTF in the same module, only the second one needs tensorflow, I was importing the package at the top level of the file using:
try:
import tensorflow as tf
except ModuleNotFoundError:
logging.error("Tensorflow not found, pip install tensorflow to use MyClassTF")
So this comes with two problems:
- If as a user, I'm importing MyClassRegular, it will make warnings about a package I don't even need or care about because I'm using a functionality that is not related to tensorflow
- If for some reason, I've installed tensorflow, it could start making warning messages, like the cuda version is not right, or not found a GPU, etc, that again, is not related to MyClassRegular.
So what comes to mind is to import the package inside the MyClassTF, I know this could go somehow against PEP 8, but I don't see a better way to handle it. So giving it a try to this option, I come to the problem that if I import the module on the init, it's not recognized by the classes methods:
class MyClassTF:
def __init__(self):
try:
import tensorflow as tf
except ModuleNotFoundError:
logging.error("Tensorflow not found, pip install tensorflow to use MyClassTF")
def train(self):
print(tf.__version__) # <--- tensorflow it's not recognized here
def predict(self):
print(tf.__version__) # <--- Again, not recognized
I could assign tensorflow to a variable like this, but it doesn't feel right:
class MyClassTF:
def __init__(self):
try:
import tensorflow as tf
self.tf = tf
except ModuleNotFoundError:
logging.error("Tensorflow not found, pip install tensorflow")
So, what would be the best pythonic way to handle this?
EDIT: both MyClassRegular, and MyClassTF are imported in the top __init__.py
file using
__all__ = ["MyClassRegular", "MyClassTF"]