Skip to content

Proposal: Property observers (willset/didset) #416

@antonsynd

Description

@antonsynd

Summary

Explore adding Swift-inspired property observers to Sharpy auto-properties. This would allow reacting to property changes without converting to fully custom getter/setter syntax.

Motivation

Currently, to add side effects (validation, logging, notification) to a property, you must convert from auto-property to fully custom function-style property — a significant syntactic rewrite. Property observers would allow "auto + side effects" without changing the property's fundamental form.

Proposed Syntax (tentative)

property health: int
    didset:
        print(f"health changed from {oldvalue} to {self.health}")
    willset(new_value):
        assert new_value >= 0

Design Considerations

  • willset fires before the value changes, receives the new value as a parameter
  • didset fires after the value changes, oldvalue is a contextual keyword referring to the previous value
  • Observers are only valid on auto-properties (not custom getter/setter)
  • Maps to C# property setter with validation/notification code before/after field assignment
  • Orthogonal to events — observers are per-property side effects, events are pub/sub
  • Consider interaction with @dataclass auto-generated properties

Prior Art

  • Swift: willSet / didSet blocks on stored properties
  • Kotlin: Delegates.observable / Delegates.vetoable
  • C#: INotifyPropertyChanged (library-level, verbose)

Context

Identified during syntax consolidation analysis (conversation: dataclass-property-syntax-analysis). Lower priority than @dataclass and mixed auto+custom property support — this is a future consideration once the property system foundation is solid.

Status

Proposal — needs RFC-level design before implementation.

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions