Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Python import order matter

Tags:

python

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.

like image 735
Dusty Avatar asked Nov 07 '14 15:11

Dusty


People also ask

What order should imports be in Python?

Imports should be grouped in the following order: Standard library imports. Related third party imports. Local application/library specific imports.

Does Python black sort imports?

isort. isort helps to sort and format imports in your Python code. Black also formats imports, but in a different way from isort's defaults which leads to conflicting changes.

What happens when a Python file is imported?

When a module is first imported, Python searches for the module and if found, it creates a module object 1, initializing it. If the named module cannot be found, a ModuleNotFoundError is raised. Python implements various strategies to search for the named module when the import machinery is invoked.


1 Answers

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.)

like image 198
John Kugelman Avatar answered Sep 21 '22 15:09

John Kugelman