Skip to content

Commit abf6b6e

Browse files
committed
Add illustration of NewType
1 parent 83ef719 commit abf6b6e

File tree

2 files changed

+54
-3
lines changed

2 files changed

+54
-3
lines changed

source-code/typing/README.md

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -24,8 +24,8 @@ Type checking can be done using [mypy](http://mypy-lang.org/index.html).
2424
1. `dict_incorrect.py`: code that counts the words in a text read from standard
2525
input. The counts are subsequently normalized to `float`, which is a type
2626
error.
27-
1. `dict_correct_type_statement.py`: same code as `dict_correct.py`, but
28-
with a type variable as type statement.
27+
1. `dict_correct_type_statement.py`: same code as `dict_correct.py`, but with a
28+
type variable as type statement.
2929
1. `people_incorrect.py`: code that defines a `People` class, stores some in a
3030
list with mistakes.
3131
1. `duck_typing.py`: example code illustrating duck typing.
@@ -42,4 +42,7 @@ Type checking can be done using [mypy](http://mypy-lang.org/index.html).
4242
1. `classes.py`: illustration of using type hints with a user-defined class.
4343
1. `classes_incorrect.py`: illustration of using type hints with a user-defined
4444
class with errors.
45-
1. `tree.py`: illustration of using type hints on more sophisticated classes, as well as generic types.
45+
1. `tree.py`: illustration of using type hints on more sophisticated classes,
46+
as well as generic types.
47+
1. `new_types.py`: illustration of using `NewType` to create specific types
48+
with specific semantics.

source-code/typing/new_types.py

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
#!/usr/bin/env python
2+
3+
from typing import NewType
4+
5+
PersonId = NewType('PersonId', int)
6+
Age = NewType('Age', int)
7+
8+
class Person:
9+
_person_id: PersonId
10+
_age: Age
11+
12+
def __init__(self, person_id: PersonId, age: Age) -> None:
13+
self._person_id = person_id
14+
self._age = age
15+
16+
@property
17+
def person_id(self) -> PersonId:
18+
return self._person_id
19+
20+
@person_id.setter
21+
def person_id(self, person_id: PersonId) -> None:
22+
self._person_id = person_id
23+
24+
@property
25+
def age(self) -> Age:
26+
return self._age
27+
28+
@age.setter
29+
def age(self, age: Age) -> None:
30+
self._age = age
31+
32+
def __repr__(self) -> str:
33+
return f'Person(person_id={self.person_id}, age={self.age})'
34+
35+
36+
if __name__ == '__main__':
37+
person = Person(PersonId(1), Age(20))
38+
print(person)
39+
person.person_id = PersonId(2)
40+
person.age = Age(30)
41+
print(person)
42+
print(person.person_id)
43+
print(person.age)
44+
print(person.person_id + 1)
45+
print(person.age + 1)
46+
print(person.person_id + person.age)
47+
person.age = PersonId(40)
48+
person.age = 25

0 commit comments

Comments
 (0)