When using an optional import, i.e. the package is only imported inside a function as I want it to be an optional dependency of my package, is there a way to type hint the return type of the function as one of the classes belonging to this optional dependency?
To give a simple example with pandas
as an optional dependency:
def my_func() -> pd.DataFrame:
import pandas as pd
return pd.DataFrame()
df = my_func()
In this case, since the import
statement is within my_func
, this code will, not surprisingly, raise:
NameError: name 'pd' is not defined
If the string literal type hint were used instead, i.e.:
def my_func() -> 'pd.DataFrame':
import pandas as pd
return pd.DataFrame()
df = my_func()
the module can now be executed without issue, but mypy
will complain:
error: Name 'pd' is not defined
How can I make the module execute successfully and retain the static type checking capability, while also having this import be optional?