4 ms·
A recent anegdote with regards to typing in Python. Let's say you have this code: class Creature: def __init__(self, name: str, hp: int, attack: int):
by wheelerof4te 5y ago
A recent anegdote with regards to typing in Python.
Let's say you have this code:
class Creature:
def __init__(self, name: str, hp: int, attack: int):
...
def attack(self, other: Creature):
...
Guess what? Since Creature is not yet defined, your very smart type-checker can't see the "other" parameter. Happened to me in VS Code.
That is the problem with features bolted on to a language where they perhaps don't belong. Now, I know that typing helps when you have simple, functional code. So, this code will work:
from dataclasses import dataclass
@dataclass
class Creature:
name: str
hp: int
attack: int
def combat_between(attacker: Creature, defender: Creature):
...
I was really surprised with this. We need better review in regards to adding additional features that may be broken on certain setups.
- orf 5y agoSimply add quotes around “Creature” and it works. > We need better review in regards to adding additional features that may be broken on certain setups. What does this even mean. The documentation explains that you need to do this, and it’s fairly obvious why you would. Type hints are one of the best features added to Python.
- wheelerof4te 5y agoYeah, "simply add quotes", indeed. Except, it is not that simple. It's not even intuitive. Typing is a great feature on paper, but in practice, it is just something we don't need in a scripting and glue language.
- tda 5y agoThat's why you can add quotes to types: def attack(self, other: 'Creature'):
- wheelerof4te 5y agoThanks, I did not know about this.
- kaashif 5y agoTo make that work you have to use `from __future__ import annotations`. see https://stackoverflow.com/questions/61544854/from-future-import-annotations https://stackoverflow.com/questions/61544854/from-future-imp... Not the most ergonomic, but there is a way to do it.
- jwilk 5y agoThis was added in Python 3.7 and it's always enabled since Python 3.10.