Skip to content

Commit

Permalink
WIP: django_stubs_ext: monkeypatch reveal_{type,locals} into builti…
Browse files Browse the repository at this point in the history
…ns (#591)

* WIP: django_stubs_ext: monkeypatch `reveal_{type,locals}` into builtins

Fixes #590

* fixup! WIP: django_stubs_ext: monkeypatch `reveal_{type,locals}` into builtins

* fixup! fixup! WIP: django_stubs_ext: monkeypatch `reveal_{type,locals}` into builtins

* Update patch.py

Co-authored-by: Nikita Sobolev <mail@sobolevn.me>
  • Loading branch information
blueyed and sobolevn committed Apr 14, 2021
1 parent 3c6f438 commit ee58b18
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 1 deletion.
8 changes: 7 additions & 1 deletion django_stubs_ext/django_stubs_ext/patch.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import builtins
from typing import Any, Generic, List, Optional, Tuple, Type, TypeVar

from django import VERSION as VERSION
Expand Down Expand Up @@ -46,15 +47,20 @@ def __repr__(self) -> str:
]


# currently just adds the __class_getitem__ dunder. if more monkeypatching is needed, add it here
def monkeypatch() -> None:
"""Monkey patch django as necessary to work properly with mypy."""

# Add the __class_getitem__ dunder.
suited_for_this_version = filter(
lambda spec: spec.version is None or VERSION[:2] <= spec.version,
_need_generic,
)
for el in suited_for_this_version:
el.cls.__class_getitem__ = classmethod(lambda cls, *args, **kwargs: cls)

# Define mypy builtins, to not cause NameError during setting up Django.
builtins.reveal_type = lambda _: None
builtins.reveal_locals = lambda: None


__all__ = ["monkeypatch"]
13 changes: 13 additions & 0 deletions django_stubs_ext/tests/test_monkeypatching.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import builtins
from contextlib import suppress
from typing import Optional

Expand Down Expand Up @@ -28,6 +29,9 @@ def fin() -> None:
with suppress(AttributeError):
delattr(el.cls, "__class_getitem__")

del builtins.reveal_type
del builtins.reveal_locals

def factory(django_version: Optional[_VersionSpec] = None) -> None:
if django_version is not None:
monkeypatch.setattr(patch, "VERSION", django_version)
Expand Down Expand Up @@ -65,3 +69,12 @@ def test_patched_version_specific(
for el in _need_generic:
if el.version is not None and django_version <= el.version:
assert el.cls[int] is el.cls


def test_patched_mypy_builtins(make_generic_classes: _MakeGenericClasses) -> None:
make_generic_classes()

assert builtins.reveal_type
assert builtins.reveal_locals

reveal_type(reveal_locals) # noqa: F821

0 comments on commit ee58b18

Please sign in to comment.