Fix `__all__` imports in `__init__.py`s
On a few places in Mesa uses __all__ imports in different __init__.pys files.
https://github.com/projectmesa/mesa/blob/2cdbcb6289c7ed0a7b086768bf5930f05c30568b/mesa/init.py#L8-L23 https://github.com/projectmesa/mesa/blob/2cdbcb6289c7ed0a7b086768bf5930f05c30568b/mesa/experimental/init.py#L3-L7
This allows easier importing of modules, but does import modules that are not even necessary or used at all. This created some problems after #2265, because for some of those imports require dependencies that are not included by default.
Follow-up on #2265, fixes https://github.com/projectmesa/mesa-examples/pull/198.
@EwoutH is this still open? I would like to work on it as a good starting point for contribution.
Hi, I’ve opened a PR addressing this issue by replacing eager imports in mesa/__init__.py with lazy loading using __getattr__.
This avoids importing optional dependencies at package import time while preserving the existing API.
PR: https://github.com/mesa/mesa/pull/3560
Would appreciate any feedback!
Let's see how PEP 810 (Explicit lazy imports) develops. It might offer some new best-practices starting with Python 3.15.
In that light I can imagine we're jumping early to 3.15, if it offers significant benefits (somebody could already research if this is the case).
By the way, we already require Python 3.12+, so I believe we could fully utilize PEP 690. I don't know if we do that already.
690 was rejected, but I agree that mimicking scipy seems sensible. Note, however, that the import times for mesa are very small compared to e.g., scipy.
I am not in favour of moving quickly to 3.15. It will render Mesa unusable on many HPC systems for several years. HPC systems generally rely on conda. To my knowledge, the default conda distribution currently uses 3.13. Most HPC systems update their libraries once or twice a year and prefer very stable distributions. So, many are likely to still be on 3.12 or even 3.10.
Consolidating the history on this while working in discrete_space, since the pattern keeps recurring:
- #2357 (Oct 2024): quick fix — wrapped the eager Solara import in
mesa/experimental/__init__.pyin a try/except. Called out at the time as a stopgap for this issue. - #3596 → #3598 (Mar 2026): same root cause, different file —
network.pydid a bareimport networkx as nxjust to defaultlayout. Fixed the same way: moved the import inside__init__, guarded byif layout is None. - #3560: an attempt at a real
__getattr__-based lazy loader formesa/__init__.py— closed pending agreement on direction here.
So the underlying problem has now been patched twice with the same manual guard, and the architecture question from #3560 is still open. Happy to help however's most useful — draft the __getattr__ proposal, hold off for PEP 810's native lazy imports once we can require Python 3.15+, or something else. Let me know how you'd like to scope this and I'll follow your lead.