import in code
breamoreboy at gmail.com
Sun Jul 22 10:38:24 EDT 2018
On 22/07/18 05:45, Cameron Simpson wrote:
> On 22Jul2018 06:43, Abdur-Rahmaan Janhangeer <arj.python at gmail.com> wrote:
>> i have found some reputable books that include import within code
>> with ...
>> import x
>> if ...
>> import y
>> def ...
>> import z
>> according to me they should be placed at the top. but an advantage of
>> it is
>> optimisation where you only load modules if necessary
>> so, import within code can be called unpythonic?
> It is discouraged, because when the imports are at the top they're
> really obvious. That is a huge gain for maintenance and readability.
> Importing a module is _usually_ pretty cheap. There are some reasons to
> put off imports until the code which needs them runs, but they are all
> fairly rare:
> Circular imports: 2 codependent modules. If you have:
> module A:
> import B
> module B:
> import B
> That won't work: the second import (whichever it turns out to be) will
> fail. One workaround is to make one of the modules put off the import. A
> better approach is usually to redesign things so that they don't do a
> mutual import (move classses etc around, or merge them). This is always
> feasible, but often is.
I don't ever recall seeing a module try to import itself, but then
perhaps you meant module B should be importing module A? :)
My fellow Pythonistas, ask not what our language can do for you, ask
what you can do for our language.
More information about the Python-list