mypy

mypy and django models: how to detect errors on nonexistent attributes

空扰寡人 提交于 2019-12-07 06:45:38
问题 Consider this model definition and usage: from django.db import models class User(models.Model): name: str = models.CharField(max_length=100) def do_stuff(user: User) -> None: # accessing existing field print(user.name.strip()) # accessing existing field with a wrong operation: will fail at runtime print(user.name + 1) # acessing nonexistent field: will fail at runtime print(user.name_abc.strip()) While running mypy on this, we will get an error for user.name + 1 : error: Unsupported operand

Classmethods in Generic Protocols with self-types, mypy type checking failure

≯℡__Kan透↙ 提交于 2019-12-07 00:22:03
问题 A little background, I essentially need to define an int wrapper type, say MyInt (among some other classes), and another generic Interval type which can accept MyInt objects as well as other types of objects. Since the types acceptable by the Interval do not fall into a neat hierarchy, I thought this would be a perfect use-case for the experimental Protocol , which in my case would require a couple of methods and a couple of @classmethod s. All the methods return a "self-type", i.e., MyInt.my

Python type hints and context managers

被刻印的时光 ゝ 提交于 2019-12-06 17:02:38
问题 How should a context manager be annotated with Python type hints? import typing @contextlib.contextmanager def foo() -> ???: yield The documentation on contextlib doesn't mention types much. The documentation on typing.ContextManager is not all that helpful either. There's also typing.Generator, which at least has an example. Does that mean I should use typing.Generator[None, None, None] and not typing.ContextManager ? import typing @contextlib.contextmanager def foo() -> typing.Generator

mypy: creating a type that accepts list of instances of subclasses

房东的猫 提交于 2019-12-06 13:19:12
Suppose I have a Child class that is a subclass of Parent class, and a function that accepts a list of instances of Parent subclasses: from typing import List class Parent: pass class Child(Parent): pass def func(objects: List[Parent]) -> None: print(objects) children = [Child()] func(children) running mypy on this produces an error: error: Argument 1 to "func" has incompatible type "List[Child]"; expected "List[Parent]" How do I create a type for this? P.S. There's a way to fix this particular error with a Sequence type: def func(objects: Sequence[Parent]) -> None: print(objects) but this

Type hinting with descriptors

心已入冬 提交于 2019-12-06 06:39:23
问题 In this pull request it looks like type hinting support for descriptors was added. However it looks like no finalized "correct" usage example was ever posted, nor does it looks like any documentation was ever added to the typing module or to Mypy. It looks like the correct usage is something like this: from typing import TypeVar T = TypeVar('T') V = TypeVar('V') class classproperty(): def __init__(self, getter: Callable[[Type[T], V]) -> None: self.getter = getter def __get__(self, instance:

mypy error, overload with Union/Optional, “Overloaded function signatures 1 and 2 overlap with incompatible return types”

喜夏-厌秋 提交于 2019-12-05 04:57:19
So, let's start with an example. Suppose we have several types that can be combined together, let's say we are using __add__ to implement this. Unfortunately, due to circumstances beyond our control, everything has to be "nullable", so we are forced to use Optional everywhere. from typing import Optional, List, overload class Foo: value: int def __init__(self, value: int) -> None: self.value = value def __add__(self, other: 'Foo') -> 'Optional[Foo]': result = self.value - other.value if result > 42: return None else: return Foo(result) class Bar: value: str def __init__(self, value: str) ->

Classmethods in Generic Protocols with self-types, mypy type checking failure

江枫思渺然 提交于 2019-12-05 03:49:24
A little background, I essentially need to define an int wrapper type, say MyInt (among some other classes), and another generic Interval type which can accept MyInt objects as well as other types of objects. Since the types acceptable by the Interval do not fall into a neat hierarchy, I thought this would be a perfect use-case for the experimental Protocol , which in my case would require a couple of methods and a couple of @classmethod s. All the methods return a "self-type", i.e., MyInt.my_method returns a MyInt . Here is a MCVE: from dataclasses import dataclass from typing import Union,

Using Mypy local stubs

我与影子孤独终老i 提交于 2019-12-05 01:57:54
I am trying the typing hint introduced by Python 3.5 and got a problem by using local stubs as the typing hint with mypy. The experiment I do is to creat kk.py containing def type_check(a): pass Also, I put kk.pyi containing def type_check(a: int):... in the same directory. In this way, I tried to trigger the error of "ncompatible types in assignment" by passing a string to type_check in kk.py. However, when I ran mypy kk.py and get no error. Thus I tried another way that mypy doc suggests, which is to set environment variable MYPYPATH to ~/some/path/stub and put kk.pyi in the directory. I got

How can mypy ignore a single line in a source file?

此生再无相见时 提交于 2019-12-04 22:57:29
I'm using mypy in my python project for type checking. I'm also using PyYAML for reading and writing the project configuration files. Unfortunately, when using the recommended import mechanism from the PyYAML documentation this generates a spurious error in a try/except clause that attempts to import native libraries: from yaml import load, dump try: from yaml import CLoader as Loader, CDumper as Dumper except ImportError: from yaml import Loader, Dumper On my system CLoader and CDumper aren't present, which results in the errors error: Module 'yaml' has no attribute 'CLoader' and error:

Python type hints and context managers

隐身守侯 提交于 2019-12-04 22:36:40
How should a context manager be annotated with Python type hints? import typing @contextlib.contextmanager def foo() -> ???: yield The documentation on contextlib doesn't mention types much. The documentation on typing.ContextManager is not all that helpful either. There's also typing.Generator , which at least has an example. Does that mean I should use typing.Generator[None, None, None] and not typing.ContextManager ? import typing @contextlib.contextmanager def foo() -> typing.Generator[None, None, None]: yield Whenever I'm not 100% sure what types a function accepts, I like to consult