I want a function to quickly check if a module is present before running other lines in the function. It may execute in several other programs in a large code base and I don't want to import sys
at the top wherever it is run.
This answer explains the procedure to check if a module is present.
>>> import sys
>>> 'unicodedata' in sys.modules
False
>>> import unicodedata
>>> 'unicodedata' in sys.modules
True
Here a number of people voice opinions on when it is okay to import inside a function.
Is the following specific usage okay?
def some_function(foo):
import sys
if 'pandas' in sys.modules:
if isinstance(foo, pd.DataFrame):
# function continues
else:
print("pandas has not been imported in the code you are testing")
The use case is checking first if a pandas data frame fulfills various conditions and if so do other operations. Thing is, looking at the code base I can't always be sure if the thing I am testing the function on is a dataframe at all, so have been doing if is instance(variable, pd.DataFrame)
. But what if the function is imported somewhere and run where there is no pandas at all? I'd rather it just realised that, than crashed the whole program or imported pandas unnecessarily.