user16776498
user16776498

Reputation:

Does separating classes in different modules have performance consequences?

Is it better to have all your classes in one module (assuming they are related somehow) in terms of performance? Because Python needs to search the module and maybe importing packages to every module takes time?

i.e:

├──animals
   └── animals.py

animals.py:

import stuff

class dog: ...

class cat: ...

class fish: ...

or

src
├── animals
│   ├── __init__.py       
│   ├── dog.py
|   |── cat.py
|   |── fish.py
└── do_stuff_with_animals.py

do_stuff_with_animals.py:

from src.animals import dog ,cat ,fish

Upvotes: 0

Views: 68

Answers (1)

Barak Itkin
Barak Itkin

Reputation: 4877

Regardless of where your modules are defined, once you did the import, the "module object" with all the definitions inside it is cached under sys.modules (from the documentation here)

You will "pay" some cost for each import (finding the file, parsing the file and compiling the python code, loading the code into memory, and running it for to evaluate), but in a long running program this shouldn't be an issue - once the modules are loaded, this is cached and module import times are typically negligible (assuming the modules only define classes and don't anything sophisticated).

Upvotes: 1

Related Questions