I read here about sorting your import statements in Python, but what if the thing you are importing needs dependencies that have not been imported yet? Is this the difference between compiled languages and interpreted? I come from a JavaScript background and the order in which you load your scripts matter, whereas Python appears not to care. Thanks.
4 Answers 4
Import order does not matter. If a module relies on other modules, it needs to import them itself. Python treats each .py file as a self-contained unit as far as what's visible in that file.
(Technically, changing import order could change behavior, because modules can have initialization code that runs when they are first imported. If that initialization code has side effects it's possible for modules to have interactions with each other. However, this would be a design flaw in those modules. Import order is not supposed to matter, so initialization code should also be written to not depend on any particular ordering.)
2 Comments
from package import * paradigm, one could also potentially overwrite definitions. This for instance happens with from math import * and from numpy import *.__init__ behavior of the module has side-effects. For example, importing TensorFlow will consume the total of GPU memory available. If you try to import Caffe after importing TensorFlow, Caffe will be unable to claim any memory resources from the GPU(s). There can be simpler things with extension modules that define conflicting settings or place locks on files. "Import" just means "execute some code". This is so ubiquitous among widely used libraries that it's not useful to say import order shouldn't matter because on-import side-effects are a bad practice.Python Import order doesnot matter when you are importing standard python libraries/modules. But, the order matters for your local application/library specific imports as you may stuck in circular dependency loop, so do look before importing.
Comments
No, it doesn't, because each python module should be self-contained and import everything it needs. This holds true for importing whole modules and only specific parts of it.
Order can matter for various nefarious reasons, including monkey patching.
from x import xx