Skip to content

Support for immutable instance variables (feature) #2795

Closed
@Stiivi

Description

@Stiivi

Provide information for the type checker about instance variables that are immutable once initialized.

Motivation

There are situations where it might be desirable that some or all of the instance variables remain unchanged during lifetime of the object. It would be great if the type checker issued an error or warning when a variable with a special annotation is assigned to outside of permitted scope.

Proposed Solution

Introduce Immutable[T]:

class Attribute:
    name: Immutable[str]
    def __init__(self, name: str) → None
        self.name = name

Assignment to Immutable variables should be allowed only in the __init__ method of a class. The following should cause an error, no matter of scope:

attr = Attribute("foo")
# Causes type checking error:
attr.name = "bar"

Error should occur even in other methods of the class that defines the Immutable variable:

class Attribute:
    name: Immutable[str]
    # ... (definition as above) ...

    def set_name(self, new_name: str) → None:
        # Should cause type checking error:
        self.name = new_name

This is an additive change, does not break existing code.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions