Skip to content

Read-only Protocol attributes #903

Answered by Akuli
bryanforbes asked this question in Q&A
Discussion options

You must be logged in to vote

You can use a Protocol with a property that does not have a setter:

class Identifiable(Protocol):
    @property
    def id(self) -> int: ...

Now object.id = 2 fails with a readable mypy error: asd.py:29: error: Property "id" defined in "Identifiable" is read-only

As a side note, it's might not be a good idea to make a variable named id or object, as those are names of built-ins, and it's not clear whether object somewhere in the middle of the code refers to object the built-in class or some variable named object. This is worst with global variables, but I don't consider it good practice with local variables either.

Replies: 1 comment 9 replies

Comment options

You must be logged in to vote
9 replies
@jonemo
Comment options

@Kentzo
Comment options

@hauntsaninja
Comment options

@jonemo
Comment options

@sigma67
Comment options

Answer selected by bryanforbes
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
7 participants