[Bug] `from mesa import Model` crashes with `ModuleNotFoundError: No module named 'networkx'` on plain `pip install mesa`
Describe the bug
A plain pip install mesa produces a broken installation. Running even
the most basic import:
from mesa import Model
crashes immediately with ModuleNotFoundError: No module named 'networkx',
despite the user never requesting any network functionality.
The bug is caused by a chain of three unconditional imports:
mesa/__init__.pyrunsimport mesa.discrete_space as discrete_spaceon every import of the mesa package.- This transitively loads
mesa/discrete_space/network.py. network.pyexecutesimport networkx as nxat the top level.
Since networkx is declared only as an optional dependency in
pyproject.toml under [project.optional-dependencies] -> network, a
plain pip install mesa never fetches it, making every import of mesa
crash unconditionally.
Confirmed in pyproject.toml on main:
# networkx is NOT in core dependencies
dependencies = [
"numpy",
"pandas",
"tqdm",
"scipy",
]
# it is gated here instead
[project.optional-dependencies]
network = [
"networkx",
]
Confirmed in mesa/__init__.py on main:
import mesa.discrete_space as discrete_space # unconditional
This bug is present in both the latest stable release (v3.5.1) and the current development branch (v4.0.0a0), meaning it is not fixed heading into 4.0.
Expected behavior
pip install mesa followed by from mesa import Model should work
with zero additional steps. If networkx is intentionally optional
(which pyproject.toml confirms it is), its absence should only raise
an error when the user explicitly tries to use network-based spaces,
not on every single import of the package.
To Reproduce
pip install mesa # plain install, no extras
python -c "from mesa import Model"
Output:
Traceback (most recent call last):
...
File ".../mesa/discrete_space/network.py", line X, in <module>
import networkx as nx
ModuleNotFoundError: No module named 'networkx'
Proposed Fix
Since pyproject.toml deliberately marks networkx as optional, the
correct fix is to make the import truly lazy inside
mesa/discrete_space/network.py, so the error only surfaces when the
user actually instantiates a network space:
# mesa/discrete_space/network.py
nx = None # sentinel
def _get_networkx():
global nx
if nx is None:
try:
import networkx as nx
except ImportError as e:
raise ImportError(
"networkx is required for network-based spaces but is not installed. "
"Install it with: pip install mesa[network]"
) from e
return nx
All internal usages of nx inside network.py should then call
_get_networkx() instead of referencing nx directly. This ensures
users who never touch network spaces are completely unaffected, and
respects the existing optional dependency architecture without requiring
any changes to pyproject.toml.
Already addressed in #3598