Handling Private/Reserved Variables in Mesa #2230
Replies: 6 comments 15 replies
-
My solution for this is quite simple, we just make a list. Model.reserved_variables = ["agents", "step", "running", ...] If the user tries to overwrite any of these variables on initialization, they get an error with a pretty error message explaining what's happening. To introduce new reserved variables, we could add a dictionary, which throws a deprecation warning if one of the keys is overwritten, with the Mesa version in which it will be reserved as value. Model.future_reserved_variables = {"agent_list": "3.0", "time": "3.1"} We document this list clearly and keep a page on what each reserved variable does. Agents can also have reserved variables in the same way, since they are often overwritten. This way we don't have to use the |
Beta Was this translation helpful? Give feedback.
-
Probably overkill
Keep internal attributes well defined and limited in scope
I am not sure. Using properties might be a convenient way forward. I think it will make it easier to raise warning if people try to overwrite internal attributes. This of course next to clear documentation of all reserved names. I would have to experiment a bit to see what is possible but some kind of metaprogramming seems the most robust way to handle this.
Probably this needs to be handled in more then one way. For example, a notes in the docstring of Model and Agent highlighting internal attributes is part of it. It should be explicitly covered in tutorials and meaningful warnings/errors should be raised. |
Beta Was this translation helpful? Give feedback.
-
While looking through various libraries for #2291, I came across an example of using # taken from psygnal._group.py
def __init_subclass__(
cls,
strict: bool = False,
signal_aliases: Mapping[str, str | None] = {},
) -> None:
"""Collects all Signal instances on the class under `cls._psygnal_signals`."""
# Collect Signals and remove from class attributes
# Use dir(cls) instead of cls.__dict__ to get attributes from super()
forbidden = {
k for k in getattr(cls, "__dict__", ()) if k.startswith("_psygnal")
}
if forbidden:
raise TypeError(
f"SignalGroup subclass cannot have attributes starting with '_psygnal'."
f" Found: {forbidden}"
) |
Beta Was this translation helpful? Give feedback.
-
I think we have all the pieces at hand to handle this now
Did I forget anything? |
Beta Was this translation helpful? Give feedback.
-
@quaquel I feel you have an idea about an implementation for this one, would you like to create one? |
Beta Was this translation helpful? Give feedback.
-
Python 3.13 includes a new
|
Beta Was this translation helpful? Give feedback.
-
This discussion is split of from
steps
counter #2223Background
Mesa models are often subclassed, raising questions about how to handle private or reserved variables to prevent conflicts or unintended overrides.
Key points
Questions for discussion
Beta Was this translation helpful? Give feedback.
All reactions