mypy

How to make mypy complain about assigning an Any to an int

独自空忆成欢 提交于 2019-12-11 06:36:51
问题 mypy --strict dutifully complains about the following code: from typing import Any, Dict def main() -> None: my_str: str = 'hello' my_int: int = my_str if __name__ == "__main__": main() by outputting: error: Incompatible types in assignment (expression has type "str", variable has type "int") However the following code is accepted without any error: from typing import Any, Dict def main() -> None: my_str: Any = 'hello' my_int: int = my_str if __name__ == "__main__": main() Is there an option

How to type Python mixin with superclass calls?

泪湿孤枕 提交于 2019-12-11 03:16:38
问题 I'm trying to use the FieldMixin from this answer in my project, but I'm having trouble getting it to pass mypy checks. The current code: class DynamicFieldsMixin(Serializer): context: Dict[str, Any] def get_field_names( self, declared_fields: OrderedDict, info: FieldInfo ) -> Set[str]: field_names: Set[str] = self.context.get( "fields", super().get_field_names(declared_fields, info) ) return field_names Inheriting from rest_framework.serializers.Serializer seems weird, and I wonder if there

mypy: how to verify a type has multiple super classes

☆樱花仙子☆ 提交于 2019-12-11 02:35:22
问题 I would like mypy to verify that a variable is subclassed from a certain base class and that it also has a specific mixin. Union only verifies that the value is of one type or another. I need to check that the value is both types. In the example, I'm making up a keyword "All" to demonstrate the behavior I'm looking for: from typing import All class Base ( object ): pass class Mixin ( object ): pass def assert_all ( x ): # type: ( All[Base,Mixin] ) -> None assert isinstance ( x, Base ) and

mypy Error TypeVar with Value Restriction and Union of Unions / Optional Cannot Pass generic container type

折月煮酒 提交于 2019-12-11 02:01:15
问题 So, the following example is obviously contrived but I tried to keep some verisimilitude to my actual situation. Now that I've whittled this down, I am sure I am missing something obvious. Consider a couple of types and a restricted Union: from typing import Union, TypeVar, Optional, Generic, overload class Foo: def __init__(self, x: int)-> None: self.x = x def frobnicate(self) -> 'Foo': return Foo((self.x + 42) // 42) class Bar: def __init__(self, y: int) -> None: self.y = y def frobnicate

Class cannot subclass 'QObject' (has type 'Any') using mypy

半腔热情 提交于 2019-12-11 01:46:53
问题 I have a class that subclasses QObject. Everyting works fine but when I run mypy on it I get the error: "error: Class cannot subclass 'QObject' (has type 'Any')" At the moment I am totally stuck. I Have been reading the mypy docs but couldn't find where the error was. Here the code: from PyQt5.QtCore import QObject class ServiceLocator(QObject): def __init__(self) -> None: super().__init__() ... Cheers. 回答1: This error occurs when mypy doesn't have type information for a class (in your case

How to annotate attribute that can be implemented as property?

百般思念 提交于 2019-12-11 00:31:17
问题 I am trying to make mypy happy with my type annotations. Here is minimal example: class FooInterface: x: int class FooWithAttribute(FooInterface): x: int = 0 class FooWithProperty(FooInterface): @property def x(self) -> int: return 0 To my human understanding everything is fine: both FooWithAttribute().x and FooWithProperty().x will return 0 which is int , no type errors. However mypy complains: error: Signature of "x" incompatible with supertype "FooInterface" Is there a way to tell mypy

How to annotate function that takes a tuple of variable length in python?

半世苍凉 提交于 2019-12-10 17:14:32
问题 I have a function that takes a tuple of different lengths as an argument: from typing import Tuple def process_tuple(t: Tuple[str]): # Do nasty tuple stuff process_tuple(("a",)) process_tuple(("a", "b")) process_tuple(("a", "b", "c")) When I annotate function like mentioned above, I get these error messages fool.py:9: error: Argument 1 to "process_tuple" has incompatible type "Tuple[str, str]"; expected "Tuple[str]" fool.py:10: error: Argument 1 to "process_tuple" has incompatible type "Tuple

mypy differences in isinstance and issubclass from python 3.5 to 3.6 in parameterized generics

社会主义新天地 提交于 2019-12-10 13:28:39
问题 Before I upgraded to python 3.6 from python 3.5 this worked: import typing issubclass(list, typing.List[int]) # returns True isinstance([1, 2 ,3], typing.List[int]) # returns True now in python 3.6 both of these raise the following exception: TypeError: Parameterized generics cannot be used with class or instance checks Is this new intended behavior or a bug? If it is intended how can I perform the checks the code above is doing in python 3.6? 回答1: It is intentional, you shouldn't be mixing

customizing typing.NamedTuple

好久不见. 提交于 2019-12-10 04:49:49
问题 I'm using NamedTuple s to hold data, and I want to add a method that can be inherited by multiple NamedTuple based classes. But when I try using multiple inheritance or subclassing NamedTuple based classes, it doesn't work. Specifically, I'm trying to automatically give all of my data classes a method that can look at the classes annotations and then call some serializing code based on that. Here are some examples of what I've tried: from typing import NamedTuple class Base1: def foo(self):

MyPy annotation for classmethod returning instance

流过昼夜 提交于 2019-12-09 08:43:03
问题 How should I annotate a @classmethod that returns an instance of cls ? Here's a bad example: class Foo(object): def __init__(self, bar: str): self.bar = bar @classmethod def with_stuff_appended(cls, bar: str) -> ???: return cls(bar + "stuff") This returns a Foo but more accurately returns whichever subclass of Foo this is called on, so annotating with -> "Foo" wouldn't be good enough. 回答1: The trick is to explicitly add an annotation to the cls parameter, in combination with TypeVar , for