Say I have a module with a bunch of objects, none of which need a third-party library. Well, almost none: one single function, call it asterix()
, needs a third-party package. asterix()
isn't the point of the module, but is convenient to have if and when needed.
It seems a shame to have to require and import a whole third-party package just for that one function. What are my options? Moving asterix()
to another module/package or vendoring it seem silly.
I have found that the best balance of quick and clean is to simply do the import within asterix()
itself, possibly with some extra try/except logic around it. It violates the principle of least surprise and the convention of having imports at the top. But I tell myself I'll always be violating something.
What does crowd wisdom say about this? Is there something glaring I'm missing?
def asterix(...):
try:
import something_special
except ModuleNotFoundError as err:
# do something about err (help the user out!)
# The special code...