Re: Down with static typing

Date: 2020-01-06 10:36 am (UTC)
avysk: (Default)
From: [personal profile] avysk
> Как написать type hint "в этом месте мне нужен экземпляр класса, имеющий метод .read() без параметров, возвращающий строку"?

https://mypy.readthedocs.io/en/latest/protocols.html#protocol-types



from abc import abstractmethod
from typing import Protocol

class SupportsRead(Protocol):
    @abstractmethod
    def read(self) -> str:
        pass


def fun(something: SupportsRead):
    print(something.read())


class Good:
    def read(self) -> str:
        return "foobar"


class Bad:
    def read(self) -> int:
        return 42


fun(Good())
fun(Bad())


foobar.py:25: error: Argument 1 to "fun" has incompatible type "Bad"; expected "SupportsRead"
foobar.py:25: note: Following member(s) of "Bad" have conflicts:
foobar.py:25: note:     Expected:
foobar.py:25: note:         def read(self) -> str
foobar.py:25: note:     Got:
foobar.py:25: note:         def read(self) -> int
Found 1 error in 1 file (checked 1 source file)


Только не забывайте, что mypy -- это не статическая типизация, а проверка type hints там, где программист счёл их нужными. Если не написать type hints, ничего не будет -- например, если убрать "-> int" в описании класса Bad, ошибка исчезнет.

> В тех проектах, где я видел использование mypy — отсутствие type hints выдавало ошибку.

Я так понимаю, что Вы не видели использование mypy.
This account has disabled anonymous posting.
If you don't have an account you can create one now.
HTML doesn't work in the subject.
More info about formatting

Profile

vitus_wagner: My photo 2005 (Default)
vitus_wagner

May 2025

S M T W T F S
    1 2 3
4 56 7 8 9 10
11 12 131415 1617
1819202122 2324
25262728293031

Most Popular Tags

Style Credit

Expand Cut Tags

No cut tags
Page generated May. 25th, 2025 12:01 am
Powered by Dreamwidth Studios