I have a package with some code for injecting some database dependency.
The folder structure is the following:
- services.py <- the interface has to be injected there
- table_interface.py
- table_mongo_db.py
- table_odbc.py
The issue comes with the two specific implementations, that respectively requires the packages pymongo
and pyodbc
, which are optionals.
The beginning of the code of table_odbc.py is the following:
import logging
import pandas as pd
try:
import pyodbc
except ModuleNotFoundError:
logging.getLogger(__name__).warning("Module pyodbc not loaded")
from .table_interface import InterfaceTable
class OdbcTable(InterfaceTable):
def __init__(
self,
odbc_connection: pyodbc.Connection, # issue there
):
self._odbc_connection = odbc_connection
def read(self):
query = "{}"
df = pd.read_sql(query, self._odbc_connection)
return df
It is roughly the same code for mongoDB, but with type hinting pymongo.collection.Collection
The code fails to import with NameError
, saying it doesn't recognize pyodbc
in the type hint (in environement that didn't install it).
I found two solutions:
- remove the type hints (which I don't want)
- in case of failing imports, define the following custom class:
try:
import pyodbc
except ModuleNotFoundError:
logging.getLogger(__name__).warning("Module pyodbc not loaded")
class pyodbc:
"""
Dummy class for type hint
"""
Connection = None
I don't like much the last solution but it is the one I am going currently with but I was wondering if an alternative exists.