Most of the topics about imports at the top of the file are about kludges to make PEP 8 happy, when someone does some slight action in the midst of imports, or about the totally different topic of relative imports. I'm curious about any runtime or other concerns of late importing a package. This topic gets close to what I'm asking, but is older and also light on specifics. I think there are some legitimate reasons to do a late import, so I'm not just asking to be pedantic.
Examples where I think a late import makes sense:
- Running a non-standard mode like a debug mode or experimental mode and you don't want to add dependency creep or import time (e.g. using matplotlib with debugging). I find I run into this a lot, I don't want to impede development or mess up someone's environment if they check out my branch to run standard mode but I have debug pieces or even just development code to smooth out before the code is ready for a final push/merge.
- Runtime corner cases: if a code rarely runs because it's not triggered often, but it has an import that will take up resources or import time (e.g. tensorflow) then just defer the import to when it's actually needed.
- Deprecation: a kwarg or something triggers the older library version so you throw a warning and import the old version and its objects to stand in for the new version. Note, this might not initially be a corner case and is why I haven't included this point there.
I don't necessarily want to debate the merits of these cases, as I don't want this topic to be too broad, but rather just use these cases as examples to consider. Style and architecture aside, are there any "gotchas" to a late import, in these cases or others? Are there performance or other runtime concerns I'm not thinking about that outweigh any potential benefits (clearly, a late import on a method or class that is frequently used would not be good practice)?