mirror of
https://github.com/Sosokker/python-howto.git
synced 2025-12-18 21:44:05 +01:00
add howto for self-referencing type hints
This commit is contained in:
parent
01bf087669
commit
de957d3151
18
self-referencing-hints.md
Normal file
18
self-referencing-hints.md
Normal file
@ -0,0 +1,18 @@
|
|||||||
|
## Self-Referencing Type Hints
|
||||||
|
|
||||||
|
Inside of a class, if you write a type hint that refers to the same class Python will raise an Error because the class is not known yet.
|
||||||
|
For example:
|
||||||
|
```python
|
||||||
|
class Money:
|
||||||
|
def __add__(self, other: Money) -> Money: # ERROR: Money is unknown
|
||||||
|
"""Return the sum of two money objects."""
|
||||||
|
... (code omitted)
|
||||||
|
```
|
||||||
|
|
||||||
|
to fix this, add the following import:
|
||||||
|
```python
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
class Money:
|
||||||
|
def __add__(self, other: Money) -> Money: # OK!
|
||||||
|
```
|
||||||
Loading…
Reference in New Issue
Block a user