In my preference order: an explicit CLI option/envvar which requires the optional dep, a flag file on the filesystem, or an ImportError attempt if you absolutely must. Use a stub/trampoline file in the conditionals so that static analyzers and laziness analysis on that file itself still work.
Comments
That's only part of the puzzle. Your program needs to branch on whether the dependency is installed or not!
"Oh you don't have optional dependency? Then do X" needs to happen at runtime right?
I explained further here: https://news.ycombinator.com/item?id=49604462
In my preference order: an explicit CLI option/envvar which requires the optional dep, a flag file on the filesystem, or an ImportError attempt if you absolutely must. Use a stub/trampoline file in the conditionals so that static analyzers and laziness analysis on that file itself still work.