Skip to content

Implement Const type to indicate non-rebindable variables/attributes #1214

Closed
@hashstat

Description

@hashstat

As a Python developer, I would like a Const type so that I can indicate that a variable or attribute may not be rebound to another value. This would be especially useful for module and class constants, but could also be helpful for instance attributes that really shouldn't be modified. Not only does it help prevent accidentally overwriting constants, it would hopefully reduce the need to use @property on non-critical attributes. Here is a contrived example:

GRUNT = 0   # type: Const
MANAGER = 1   # type: Const


class Employee:
    kind = GRUNT   # type: Const

    def __init__(self, idnum: int, name: str):
        self.id = idnum   # type: Const
        self.name = name


class Manager(Employee):
    kind = MANAGER   # type: Const

kind = MANAGER # type: Const reqiures the Const type to rebind kind without an error just as a const variable in C requires a cast during reassignment to quiet compiler warnings/errors.

I'm not sure if it makes sense to allow Const to take parameters as the type can be inferred in most cases. One might want other variables, such as those passed into functions, to be const, in which case it makes sense to allow Const to take parameters. Here is an example:

def frobnicate(kind: Const[int]) -> None:
    kind = 5   # Error
    kind = 6   # type: Const  # Okay

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions