TGViewer
Питонические атаки Питонические атаки @pythonic_attacks · 1.15K subscribers
Post #530 1.11K

Forwarded from Python etc

The typing.assert_type function (added in Python 3.11) does nothing in runtime as most of the stuff from the typing module. However, if the type of the first argument doesn't match the type provided as the second argument, the type checker will return an error. It can be useful to write simple "tests" for your library to ensure it is well annotated.

For example, you have a library that defines a lot of decorators, like this:

from typing import Callable, TypeVar

C = TypeVar('C', bound=Callable)

def good_dec(f: C) -> C:
return f

def bad_dec(f) -> Callable:
return f


We want to be 100% sure that all decorators preserve the original type of decorated function. So, let's write a test for it:

from typing import Callable, assert_type

@good_dec
def f1(a: int) -> str: ...

@bad_dec
def f2(a: int) -> str: ...

assert_type(f1, Callable[[int], str]) # ok
assert_type(f2, Callable[[int], str]) # not ok
  • 👍 8
  • 💩 4
  • ❤ 1
  • 🔥 1
More from @pythonic_attacks
  1. May 24, 2026GPT-5.5 по дефолту предпочитает использовать uv. Совпадение? Абсолютно точно нет. Логично…
  2. Mar 19, 2026Новость вызывает столько противоречивых мыслей, что я даже прерву радио молчание. С одной…
  3. Mar 19, 2026https://openai.com/index/openai-to-acquire-astral/ & https://astral.sh/blog/openai Это не…
  4. Nov 17, 2025Ну что же.. Мы совместно с Эммой Смит опубликовали Pre-PEP о добавлении Раста в CPython. В…
  5. May 19, 2025Вышел трейлер документалки о Python. Что-то на уровне Marvel, возможно даже выше https://w…
  6. May 15, 2025All good things come to an end Что ж, скажем Майкрософту спасибо, что 4 года содержал кома…
Threads Profile ViewerView any public Threads profile without an account.Open ThreadLook →Writing with AI? Make it sound human.Metric37 rewrites AI drafts so they read naturally. Free AI detector, 1,500 words free.Try Metric37 →