importing down in code rather than at top of file.

Nobody nobody at nowhere.invalid
Mon Aug 29 18:05:51 EDT 2016


On Tue, 30 Aug 2016 04:15:05 +1000, Chris Angelico wrote:

> Don't imagine; test.

Testing alone isn't really good enough. There may be perfectly valid
reasons to avoid the import which won't show up in anything less than the
most thorough testing imaginable.

Personally I wouldn't defer an import just because it might be slow,
particularly if the criterion affecting whether the import actually occurs
is "probabilistic".

[If it might be slow because the module is doing stuff it really
shouldn't, like executing external commands during import, I'd probably
just avoid the package altogether.]

If the import /might/ happen as a result of normal usage, I'd want any
failure to occur when the parent module is imported, not at some rather
arbitrary later point.

If I defer imports, it's because they're only used for features which are
in some sense optional. And the documentation will state the conditions
under which the import is performed (if it's for a specific method, it
will be in the method's docstring).




More information about the Python-list mailing list