[SOLVED] does separating classes in diffrent 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?


   └── animals.py


import stuff

class dog: ...

class cat: ...

class fish: ...


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


from src.animals import dog ,cat ,fish


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

Answered By – Barak Itkin

Answer Checked By – Terry (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *