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
150
Typing Django
Sobolev Nikita
March 27, 2020
Tweet
Share
More Decks by Sobolev Nikita
See All by Sobolev Nikita
PythoNN: Василий Рябов – "Парсинг бинарных данных с помощью ctypes, или пишем на питоне как на Си"
sobolevn
0
82
GitHub Planet - OpenSource
sobolevn
0
150
Polymorphism and Typeclasses
sobolevn
2
96
New GitHub Features
sobolevn
0
32
Problems of static analysis in Python
sobolevn
0
50
Announcing typed-linter
sobolevn
0
180
About GitHub Stars
sobolevn
0
140
Functional programming for beginners
sobolevn
0
210
Practical microtasks
sobolevn
0
220
Other Decks in Programming
See All in Programming
Goのmultiple errorsについて (2024年4月版)
syumai
3
710
Netty Chicago Java User Group 2024-04-17
sullis
0
170
冗長なエラーログを削減し、スタックトレースを手に入れる / Reducing Verbose Error Logs and Obtaining Stack Traces
upamune
0
560
Milestoner
bkuhlmann
1
410
ゆるい個人開発のススメ
kuroppe1819
10
990
TYPO3 v13 – The road to LTS: What's new and new APIs
luisasofie_xoxo
0
200
Random\Randomizer クラスで日常のあれこれを解決しよう! / Random\Randomizer class solves familiar trouble
cocoeyes02
0
240
Git Lint
bkuhlmann
4
750
Ruby Pattern Matching
bkuhlmann
0
930
Fragment Composition of GraphQL
quramy
7
960
GitHub Copilotのススメ
marcy731
1
200
Hanami and htmx
bkuhlmann
0
210
Featured
See All Featured
Automating Front-end Workflow
addyosmani
1356
200k
Design by the Numbers
sachag
274
18k
StorybookのUI Testing Handbookを読んだ
zakiyama
13
4.6k
The Success of Rails: Ensuring Growth for the Next 100 Years
eileencodes
30
6k
Dealing with People You Can't Stand - Big Design 2015
cassininazir
357
22k
4 Signs Your Business is Dying
shpigford
175
21k
Java REST API Framework Comparison - PWX 2021
mraible
PRO
18
6.9k
What's new in Ruby 2.0
geeforr
337
31k
How to train your dragon (web standard)
notwaldorf
73
5.2k
Understanding Cognitive Biases in Performance Measurement
bluesmoon
7
1k
CoffeeScript is Beautiful & I Never Want to Write Plain JavaScript Again
sstephenson
155
14k
Building a Scalable Design System with Sketch
lauravandoore
456
32k
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