Upgrade to Pro
— share decks privately, control downloads, hide ads and more …
Speaker Deck
Features
Speaker Deck
PRO
Sign in
Sign up for free
Search
Search
Typing Django
Search
Sobolev Nikita
March 27, 2020
Programming
0
350
Typing Django
Sobolev Nikita
March 27, 2020
Tweet
Share
More Decks by Sobolev Nikita
See All by Sobolev Nikita
Михаил Гурбанов – Are you NATS? @ PythoNN
sobolevn
0
58
Дмитрий Бровкин – Почему исправление опечаток сложнее, чем кажется, и как мы с этим српавляемся @ PythoNN
sobolevn
0
37
Алексей Гончарук – Современный веб с темлейтами @ PythoNN
sobolevn
0
110
Алексей Голобурдин – Демистификация PostgreSQL-индексов @ PythoNN
sobolevn
0
160
PythoNN – Александр Гончаров
sobolevn
0
67
PythoNN – Андрей Пронин
sobolevn
0
130
PythoNN: Василий Рябов – "Парсинг бинарных данных с помощью ctypes, или пишем на питоне как на Си"
sobolevn
0
250
GitHub Planet - OpenSource
sobolevn
0
280
Polymorphism and Typeclasses
sobolevn
2
170
Other Decks in Programming
See All in Programming
go test -json そして testing.T.Attr / Kyoto.go #63
utgwkk
2
210
ProxyによるWindow間RPC機構の構築
syumai
2
590
MCPでVibe Working。そして、結局はContext Eng(略)/ Working with Vibe on MCP And Context Eng
rkaga
5
1.2k
Trem on Rails - Prompt Engineering com Ruby
elainenaomi
1
100
旅行プランAIエージェント開発の裏側
ippo012
1
600
TROCCO×dbtで実現する人にもAIにもやさしいデータ基盤
nealle
0
400
FindyにおけるTakumi活用と脆弱性管理のこれから
rvirus0817
0
370
Langfuseと歩む生成AI活用推進
licux
3
320
CSC305 Summer Lecture 12
javiergs
PRO
0
130
DockerからECSへ 〜 AWSの海に出る前に知っておきたいこと 〜
ota1022
5
1.9k
パスタの技術
yusukebe
1
560
Design Foundational Data Engineering Observability
sucitw
2
120
Featured
See All Featured
The Power of CSS Pseudo Elements
geoffreycrofte
77
5.9k
No one is an island. Learnings from fostering a developers community.
thoeni
21
3.4k
A Tale of Four Properties
chriscoyier
160
23k
Fashionably flexible responsive web design (full day workshop)
malarkey
407
66k
How to train your dragon (web standard)
notwaldorf
96
6.2k
実際に使うSQLの書き方 徹底解説 / pgcon21j-tutorial
soudai
PRO
185
54k
Typedesign – Prime Four
hannesfritz
42
2.8k
Into the Great Unknown - MozCon
thekraken
40
2k
How STYLIGHT went responsive
nonsquared
100
5.8k
Put a Button on it: Removing Barriers to Going Fast.
kastner
60
4k
Connecting the Dots Between Site Speed, User Experience & Your Business [WebExpo 2025]
tammyeverts
8
510
Statistics for Hackers
jakevdp
799
220k
Transcript
Никита Соболев github.com/sobolevn
>_ X Типизация Django
Зачем?
Затем!
Затем! > Легче навигация по коду
Затем! > Легче навигация по коду > Быстрее обратная связь
Затем! > Легче навигация по коду > Быстрее обратная связь
> Совпадает с остальным стеком
>_ X Проблемы
А их много:
А их много: > Гигантская (и плохая) кодовая база без
типов
А их много: > Гигантская (и плохая) кодовая база без
типов > Нет прав на её редактирование (!)
А их много: > Гигантская (и плохая) кодовая база без
типов > Нет прав на её редактирование (!) > Куча магии
А их много: > Гигантская (и плохая) кодовая база без
типов > Нет прав на её редактирование (!) > Куча магии > Нет поддержки нового API типизации
>_ X Аннотация кода
MonkeyType github.com/Instagram/MonkeyType
from some.module import add add(1, 2)
monkeytype run myscript.py monkeytype stub some.module
def add(a: int, b: int) -> int: ...
None
И волонтеры!
None
None
Тысячи их! Спасибо.
>_ X Плагин для mypy
class User(models.Model): score = models.IntegerField()
class User(models.Model): score = models.IntegerField(null=True)
User.objects.filter(score=1) # ok! User.objects.filter(score__exact=1) # ok! User.objects.filter(score__exact='1') # Expected: int,
specified: str
django-stubs умеет почти все!
Чего не умеет?
Чего не умеет? > `QuerySet.as_manager()`
Чего не умеет? > `QuerySet.as_manager()` > Известные баги с `Manager.from_queryset()`
Чего не умеет? > `QuerySet.as_manager()` > Известные баги с `Manager.from_queryset()`
> Поддержка нескольких версий Django
Фичи!
class Blog(models.Model): title = models.CharField() num_posts = models.IntegerField(null=True) Blog.objects.values('title').get() #
type: TypedDict({'title': builtins.str}) blog: Blog blog.num_posts # type: Optional[int]
Как оно внутри?
def _callback(ctx: FunctionContext) -> mypy.types.Type: return AnyType() class _ExamplePlugin(Plugin): def
get_function_hook( self, fullname: str, ) -> Optional[Callable]: if fullname == 'django.db.models.fields.CharField': return _callback def plugin(version: str) -> Type[Plugin]: """Plugin's public API and entrypoint.""" return _ExamplePlugin
def _callback(ctx: FunctionContext) -> mypy.types.Type: return AnyType() class _ExamplePlugin(Plugin): def
get_function_hook( self, fullname: str, ) -> Optional[Callable]: if fullname == 'django.db.models.fields.CharField': return _callback def plugin(version: str) -> Type[Plugin]: """Plugin's public API and entrypoint.""" return _ExamplePlugin
def _callback(ctx: FunctionContext) -> mypy.types.Type: return AnyType() class _ExamplePlugin(Plugin): def
get_function_hook( self, fullname: str, ) -> Optional[Callable]: if fullname == 'django.db.models.fields.CharField': return _callback def plugin(version: str) -> Type[Plugin]: """Plugin's public API and entrypoint.""" return _ExamplePlugin
Ответственность плагина > Уточнение типов > Добавление магических атрибутов >
Прочая дичь!
django.setup()
Хотите глубже?
Как глубока кроличья нора?
Как глубока кроличья нора? > https://mypy.readthedocs.io/en/ stable/extending_mypy.html
Как глубока кроличья нора? > https://mypy.readthedocs.io/en/ stable/extending_mypy.html > https://github.com/typeddjango/ django-stubs/blob/master/
mypy_django_plugin/main.py
>_ X Тестирование типизации
None
None
None
# pytest-mypy-plugins # ./typesafety/test_first.yml - case: test_first main: | from
myapp import a reveal_type(a(1)) # N: Revealed type is 'builtins.float*' files: - path: myapp.py content: | def a(num: int) -> float: return float(num)
>_ X Будущее
Есть хорошие новости
None
Есть интересные новости
if DJANGO_3_0: ... # type specific for 3.0 else: ...
# type specific for other versions
Есть плохие новости
from django.models import QuerySet from myapp.models import User def filter_active_users()
-> QuerySet[User]: return User.objects.filter(is_active=True)
from django.models import QuerySet from myapp.models import User def filter_active_users()
-> 'QuerySet[User]': return User.objects.filter(is_active=True)
None
None
>_ X Попробуй!
github.com/wemake- services/wemake- django-template
>_ X Выводы
Сегодня мы многое поняли
Но что?
Но что? > Типизация – тяжело налазит на магию
Но что? > Типизация – тяжело налазит на магию >
Есть инструменты, которые помогут портировать нетипизированный проект в новый мир
Но что? > Типизация – тяжело налазит на магию >
Есть инструменты, которые помогут портировать нетипизированный проект в новый мир > Плагины справятся со всем остальным!
Что осталось за кадром?
Что осталось за кадром? > SemAnal / NewSemAnal
Что осталось за кадром? > SemAnal / NewSemAnal > Incremental
mode
Что осталось за кадром? > SemAnal / NewSemAnal > Incremental
mode > dmypy
Что осталось за кадром? > SemAnal / NewSemAnal > Incremental
mode > dmypy > Боль и страдания
Ссылки
Ссылки > https://github.com/typeddjango/ django-stubs
Ссылки > https://github.com/typeddjango/ django-stubs > https://github.com/typeddjango/ djangorestframework-stubs
Ссылки > https://github.com/typeddjango/ django-stubs > https://github.com/typeddjango/ djangorestframework-stubs > https://github.com/typeddjango/ pytest-mypy-plugins
Еще (полезные!) ссылки
Еще (полезные!) ссылки > https://github.com/typeddjango/ awesome-python-typing
Еще (полезные!) ссылки > https://github.com/typeddjango/ awesome-python-typing > https://sobolevn.me/2019/08/ typechecking-django-and-drf
Еще (полезные!) ссылки > https://github.com/typeddjango/ awesome-python-typing > https://sobolevn.me/2019/08/ typechecking-django-and-drf >
https://sobolevn.me/2019/08/ testing-mypy-types
Еще (полезные!) ссылки > https://github.com/typeddjango/ awesome-python-typing > https://sobolevn.me/2019/08/ typechecking-django-and-drf >
https://sobolevn.me/2019/08/ testing-mypy-types > https://sobolevn.me/2019/10/ testing-django-migrations
t.me/ opensource_findings 56
drylabs.io/py-quarantine
sobolevn.me Вопросы? github.com/sobolevn