Skip to content

Feature: Use Enum for Signal Types in mesa_signals for Type Safety #3055

@codebyNJ

Description

@codebyNJ

The mesa_signals module uses plain strings for signal types, which lacks type safety and IDE support. There's a FIXME comment at line 48 in mesa/experimental/mesa_signals/mesa_signal.py acknowledging this:

# fixme can we make this an inner class enum?

Issues:

  • Typos caught only at runtime, not by IDE/type checkers
  • No autocomplete for available signal types
  • Hard to discover what signals an observable emits

To Reproduce

from mesa.experimental.mesa_signals import Observable, HasObservables

class MyModel(HasObservables):
    wealth = Observable()
    
    def __init__(self):
        super().__init__()
        self._wealth = 0

model = MyModel()

# Typo only caught at runtime
model.observe("wealth", "chang", lambda s: print(s.new))  # Should be "change"
# ValueError: you are trying to subscribe to a signal of chang on Observable wealth, which does not emit this signal_type

Current Behavior

# Must use magic strings
model.observe("wealth", "change", handler)  # No autocomplete, easy to typo

# No way to discover available signals without reading source

Expected Behavior

from mesa.experimental.mesa_signals import SignalType

# Type-safe with autocomplete
model.observe("wealth", SignalType.CHANGE, handler)  # IDE suggests: CHANGE, DIRTY

# Typos caught by IDE/type checker immediately
model.observe("wealth", SignalType.CHANG, handler)  # AttributeError in IDE

# Self-documenting
list(SignalType)  # [SignalType.CHANGE, SignalType.DIRTY]

Proposed Solution

Add a SignalType enum that inherits from str for backward compatibility:

from enum import Enum

class SignalType(str, Enum):
    """Signal types for observables."""
    CHANGE = "change"
    DIRTY = "dirty"  # For future use
    
    def __str__(self):
        return self.value

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions