Read-only Protocol
attributes
#903
-
Is there a way to mark an attribute of a interface Identifiable {
readonly id: number;
}
class Person {
id: number;
name: string;
constructor(id: number, name: string) {
this.id = id;
this.name = name;
}
}
class Animal {
readonly id: number;
species: string;
constructor(id: number, species: string) {
this.id = id;
this.species = species;
}
}
function printID(object: Identifiable) {
console.log(object.id);
// object.id = 2 would error because of the readonly property
}
const person = new Person(1, 'John Doe');
const animal = new Animal(2, 'Dog');
printID(person); // OK
printID(animal); // OK Using from typing import Protocol
class Identifiable(Protocol):
id: int # how to mark this as read-only?
class Person:
id: int
name: str
def __init__(self, id: int, name: str) -> None:
self.id = id
self.name = name
class Animal:
__id: int
species: str
def __init__(self, id: int, species: str) -> None:
self.__id = id
self.species = species
@property
def id(self) -> int:
return self.__id
def print_id(object: Identifiable) -> None:
print(object.id)
# object.id = 2 will not error because id is declared read/write
person = Person(1, 'John Doe')
animal = Animal(2, 'Dog')
print_id(person) # OK
print_id(animal) # not OK because animal.id is not writable |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 9 replies
-
You can use a class Identifiable(Protocol):
@property
def id(self) -> int: ... Now As a side note, it's might not be a good idea to make a variable named |
Beta Was this translation helpful? Give feedback.
You can use a
Protocol
with a property that does not have a setter: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
orobject
, as those are names of built-ins, and it's not clear whetherobject
somewhere in the middle of the code refers toobject
the built-in class or some variable namedobject
. This is worst with global variables, but I don't consider it good practice with local variables either.