Slide 1

Slide 1 text

Никита Соболев github.com/sobolevn

Slide 2

Slide 2 text

>_ X Типизация Django

Slide 3

Slide 3 text

Зачем?

Slide 4

Slide 4 text

Затем!

Slide 5

Slide 5 text

Затем! > Легче навигация по коду

Slide 6

Slide 6 text

Затем! > Легче навигация по коду > Быстрее обратная связь

Slide 7

Slide 7 text

Затем! > Легче навигация по коду > Быстрее обратная связь > Совпадает с остальным стеком

Slide 8

Slide 8 text

>_ X Проблемы

Slide 9

Slide 9 text

А их много:

Slide 10

Slide 10 text

А их много: > Гигантская (и плохая) кодовая база без типов

Slide 11

Slide 11 text

А их много: > Гигантская (и плохая) кодовая база без типов > Нет прав на её редактирование (!)

Slide 12

Slide 12 text

А их много: > Гигантская (и плохая) кодовая база без типов > Нет прав на её редактирование (!) > Куча магии

Slide 13

Slide 13 text

А их много: > Гигантская (и плохая) кодовая база без типов > Нет прав на её редактирование (!) > Куча магии > Нет поддержки нового API типизации

Slide 14

Slide 14 text

>_ X Аннотация кода

Slide 15

Slide 15 text

MonkeyType github.com/Instagram/MonkeyType

Slide 16

Slide 16 text

from some.module import add add(1, 2)

Slide 17

Slide 17 text

monkeytype run myscript.py monkeytype stub some.module

Slide 18

Slide 18 text

def add(a: int, b: int) -> int: ...

Slide 19

Slide 19 text

No content

Slide 20

Slide 20 text

И волонтеры!

Slide 21

Slide 21 text

No content

Slide 22

Slide 22 text

No content

Slide 23

Slide 23 text

Тысячи их! Спасибо.

Slide 24

Slide 24 text

>_ X Плагин для mypy

Slide 25

Slide 25 text

class User(models.Model): score = models.IntegerField()

Slide 26

Slide 26 text

class User(models.Model): score = models.IntegerField(null=True)

Slide 27

Slide 27 text

User.objects.filter(score=1) # ok! User.objects.filter(score__exact=1) # ok! User.objects.filter(score__exact='1') # Expected: int, specified: str

Slide 28

Slide 28 text

django-stubs умеет почти все!

Slide 29

Slide 29 text

Чего не умеет?

Slide 30

Slide 30 text

Чего не умеет? > `QuerySet.as_manager()`

Slide 31

Slide 31 text

Чего не умеет? > `QuerySet.as_manager()` > Известные баги с `Manager.from_queryset()`

Slide 32

Slide 32 text

Чего не умеет? > `QuerySet.as_manager()` > Известные баги с `Manager.from_queryset()` > Поддержка нескольких версий Django

Slide 33

Slide 33 text

Фичи!

Slide 34

Slide 34 text

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]

Slide 35

Slide 35 text

Как оно внутри?

Slide 36

Slide 36 text

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

Slide 37

Slide 37 text

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

Slide 38

Slide 38 text

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

Slide 39

Slide 39 text

Ответственность плагина > Уточнение типов > Добавление магических атрибутов > Прочая дичь!

Slide 40

Slide 40 text

django.setup()

Slide 41

Slide 41 text

Хотите глубже?

Slide 42

Slide 42 text

Как глубока кроличья нора?

Slide 43

Slide 43 text

Как глубока кроличья нора? > https://mypy.readthedocs.io/en/ stable/extending_mypy.html

Slide 44

Slide 44 text

Как глубока кроличья нора? > https://mypy.readthedocs.io/en/ stable/extending_mypy.html > https://github.com/typeddjango/ django-stubs/blob/master/ mypy_django_plugin/main.py

Slide 45

Slide 45 text

>_ X Тестирование типизации

Slide 46

Slide 46 text

No content

Slide 47

Slide 47 text

No content

Slide 48

Slide 48 text

No content

Slide 49

Slide 49 text

# 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)

Slide 50

Slide 50 text

>_ X Будущее

Slide 51

Slide 51 text

Есть хорошие новости

Slide 52

Slide 52 text

No content

Slide 53

Slide 53 text

Есть интересные новости

Slide 54

Slide 54 text

if DJANGO_3_0: ... # type specific for 3.0 else: ... # type specific for other versions

Slide 55

Slide 55 text

Есть плохие новости

Slide 56

Slide 56 text

from django.models import QuerySet from myapp.models import User def filter_active_users() -> QuerySet[User]: return User.objects.filter(is_active=True)

Slide 57

Slide 57 text

from django.models import QuerySet from myapp.models import User def filter_active_users() -> 'QuerySet[User]': return User.objects.filter(is_active=True)

Slide 58

Slide 58 text

No content

Slide 59

Slide 59 text

No content

Slide 60

Slide 60 text

>_ X Попробуй!

Slide 61

Slide 61 text

github.com/wemake- services/wemake- django-template

Slide 62

Slide 62 text

>_ X Выводы

Slide 63

Slide 63 text

Сегодня мы многое поняли

Slide 64

Slide 64 text

Но что?

Slide 65

Slide 65 text

Но что? > Типизация – тяжело налазит на магию

Slide 66

Slide 66 text

Но что? > Типизация – тяжело налазит на магию > Есть инструменты, которые помогут портировать нетипизированный проект в новый мир

Slide 67

Slide 67 text

Но что? > Типизация – тяжело налазит на магию > Есть инструменты, которые помогут портировать нетипизированный проект в новый мир > Плагины справятся со всем остальным!

Slide 68

Slide 68 text

Что осталось за кадром?

Slide 69

Slide 69 text

Что осталось за кадром? > SemAnal / NewSemAnal

Slide 70

Slide 70 text

Что осталось за кадром? > SemAnal / NewSemAnal > Incremental mode

Slide 71

Slide 71 text

Что осталось за кадром? > SemAnal / NewSemAnal > Incremental mode > dmypy

Slide 72

Slide 72 text

Что осталось за кадром? > SemAnal / NewSemAnal > Incremental mode > dmypy > Боль и страдания

Slide 73

Slide 73 text

Ссылки

Slide 74

Slide 74 text

Ссылки > https://github.com/typeddjango/ django-stubs

Slide 75

Slide 75 text

Ссылки > https://github.com/typeddjango/ django-stubs > https://github.com/typeddjango/ djangorestframework-stubs

Slide 76

Slide 76 text

Ссылки > https://github.com/typeddjango/ django-stubs > https://github.com/typeddjango/ djangorestframework-stubs > https://github.com/typeddjango/ pytest-mypy-plugins

Slide 77

Slide 77 text

Еще (полезные!) ссылки

Slide 78

Slide 78 text

Еще (полезные!) ссылки > https://github.com/typeddjango/ awesome-python-typing

Slide 79

Slide 79 text

Еще (полезные!) ссылки > https://github.com/typeddjango/ awesome-python-typing > https://sobolevn.me/2019/08/ typechecking-django-and-drf

Slide 80

Slide 80 text

Еще (полезные!) ссылки > https://github.com/typeddjango/ awesome-python-typing > https://sobolevn.me/2019/08/ typechecking-django-and-drf > https://sobolevn.me/2019/08/ testing-mypy-types

Slide 81

Slide 81 text

Еще (полезные!) ссылки > 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

Slide 82

Slide 82 text

t.me/ opensource_findings 56

Slide 83

Slide 83 text

drylabs.io/py-quarantine

Slide 84

Slide 84 text

sobolevn.me Вопросы? github.com/sobolevn