mypy

MyPy annotation for classmethod returning instance

和自甴很熟 提交于 2019-12-03 11:06:00
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. The trick is to explicitly add an annotation to the cls parameter, in combination with TypeVar , for generics , and Type , to represent a class rather then the instance itself , like so: from typing import

Python Type Hints: Specifying a type to be a List of numbers (ints and/or floats)?

三世轮回 提交于 2019-12-03 10:47:02
How do I specific a function can take a list of numbers which can be ints or floats? I tried making a new type using Union like so: num = Union[int, float] def quick_sort(arr: List[num]) -> List[num]: ... However, mypy didn't like this: quickSortLomutoFirst.py:32: error: Argument 1 to "quickSortOuter" has incompatible type List[int]; expected List[Union[int, float]] Is there a Type that encompasses ints and floats? The short answer to your question is you should use either TypeVars or Sequence -- using List[Union[int, float]] would actually potentially introduce a bug into your code! In short,

How to use Generic (higher-kinded) type variables in python's type hinting system?

混江龙づ霸主 提交于 2019-12-02 07:02:59
问题 Suppose I want to write a generic class using mypy, but the type argument for the class is itself a generic type. For example: from typing import TypeVar, Generic, Callable A = TypeVar("A") B = TypeVar("B") T = TypeVar("T") class FunctorInstance(Generic[T]): def __init__(self, map: Callable[[Callable[[A], B], T[A]], T[B]]): self._map = map def map(self, x: T[A], f: Callable[[A], B]) -> T[B]: return self._map(f, x) When I try to call mypy in the definition above I get an error: $ mypy

How to use Generic (higher-kinded) type variables in python's type hinting system?

て烟熏妆下的殇ゞ 提交于 2019-12-02 04:25:47
Suppose I want to write a generic class using mypy, but the type argument for the class is itself a generic type. For example: from typing import TypeVar, Generic, Callable A = TypeVar("A") B = TypeVar("B") T = TypeVar("T") class FunctorInstance(Generic[T]): def __init__(self, map: Callable[[Callable[[A], B], T[A]], T[B]]): self._map = map def map(self, x: T[A], f: Callable[[A], B]) -> T[B]: return self._map(f, x) When I try to call mypy in the definition above I get an error: $ mypy typeclasses.py typeclasses.py:9: error: Type variable "T" used with arguments typeclasses.py:12: error: Type

Mypy falsely reports error on union-typed variable when branching on type

旧街凉风 提交于 2019-12-01 23:42:39
问题 I ran into an issue when using mypy and have been able to find any help/reports regarding it. The following simplified code and error message should be self-explanatory: #!/usr/bin/env python3 from typing import List, Union class Corpus: path: List[str] def __init__(self, path:Union[str,List[str]]) -> None: if type(path) == str: self.path = [path] else: self.path = path Mypy gives the following errors: simplified.py:10: error: List item 0 has incompatible type "Union[str, List[str]]";

Mypy error - incompatible types in assignment

◇◆丶佛笑我妖孽 提交于 2019-12-01 03:42:24
问题 My function looks like this simplified code sample: def my_func() -> dict: result = {"success": False} if condition: result["success"] = True return result else: result["message"] = "error message" return result When I run Mypy (version 0.52) I get this error: error: Incompatible types in assignment (expression has type "str", target has type "bool") and the error is pointing to the second last line in my code sample. Why mypy is returning this error? is my code invalid (in any way) or is

Specify length of Sequence or List with Python typing module

情到浓时终转凉″ 提交于 2019-11-30 22:14:02
问题 I'm giving the Python typing module a shot. I know that it's valid to specify the length of a List like the following*: List[float, float, float] # List of 3 floats <-- NOTE: this is not valid Python Is there any shorthand for longer lists? What if I want to set it to 10 floats? List[float * 10] # This doesn't work. Any idea if this is possible, this would be handy. *NOTE: It turns out that supplying multiple arguments to Sequence[] (and its subclasses) in this manner is currently NOT valid

Python >=3.5: Checking type annotation at runtime

吃可爱长大的小学妹 提交于 2019-11-30 07:19:00
Does the typing module (or any other module) exhibit an API to typecheck a variable at runtime, similar to isinstance() but understanding the type classes defined in typing ? I'd like to be to run something akin to: from typing import List assert isinstance([1, 'bob'], List[int]), 'Wrong type' There is no such function in the typing module, and most likely there won't ever be. Checking whether an object is an instance of a class - which only means "this object was created by the class' constructor" - is a simple matter of testing some tagging. However, checking whether an object is an

Python >=3.5: Checking type annotation at runtime

六眼飞鱼酱① 提交于 2019-11-29 02:49:58
问题 Does the typing module (or any other module) exhibit an API to typecheck a variable at runtime, similar to isinstance() but understanding the type classes defined in typing ? I'd like to be to run something akin to: from typing import List assert isinstance([1, 'bob'], List[int]), 'Wrong type' 回答1: There is no such function in the typing module, and most likely there won't ever be. Checking whether an object is an instance of a class - which only means "this object was created by the class'

A way to subclass NamedTuple for purposes of typechecking

主宰稳场 提交于 2019-11-28 12:03:15
I have several namedtuples that share some fields. I have a function that accepts these tuples and is guaranteed to only interact with the shared fields. I want to typecheck such code in mypy. An example of the code would be: from typing import NamedTuple class Base(NamedTuple): x: int y: int class BaseExtended(NamedTuple): x: int y: int z: str def DoSomething(tuple: Base): return tuple.x + tuple.y base = Base(3, 4) base_extended = BaseExtended(5, 6, 'foo') DoSomething(base) DoSomething(base_extended) When I run mypy on this code I get a predictable error: mypy_example.py:20: error: Argument 1