from typing import Union def foo(X: Union[int, str]) -> bool: if isinstance(X, str): reveal_type(X) # str def g(y: int) -> bool: reveal_type(X) # Union[int, str] return len(X) > y # <<<<< error: Argument 1 to "len" has incompatible type "Union[int, str]"; expected "Sized" return g(10) reveal_type(X) # int return bool(X)
Any. I'm currently running into a snag where I don't know how to deal with a
NewTypethat I defined - what I'm trying to do results in a mypy error. Please find below a minimal reproduction of the problem. Does anyone have any advice or am I forced to leave it as
# test.py from dataclasses import dataclass from typing import NewType A = NewType("A", str) @dataclass class Test: a: A
# stubgen'd test.pyi from typing import Any A: Any class Test: a: A def __init__(self, a: Any) -> None: ...
# trying to remove 'Any' as much as possible from typing import Type A: Type[str] class Test: a: A # mypy error: "test.A" is not valid as a type def __init__(self, a: A) -> None: ... # mypy error: "test.A" is not valid as a type
% dmypy check -- --local-partial-types dtests/dtests.py dtests/tests Success: no issues found in 430 source files % mypy --local-partial-types dtests/dtests.py dtests/tests dtests/dtestlib/scales/AbstractIterableComparator.py:36: error: Cannot determine type of '_result' dtests/dtestlib/scales/AbstractIterableComparator.py:39: error: Need type annotation for '_diff' (hint: "_diff: List[<type>] = ...") dtests/dtestlib/scales/AbstractIterableComparator.py:72: error: Incompatible types in assignment (expression has type "None", variable has type "List[Any]") dtests/dtestlib/scales/TypeStrictComparator.py:28: error: Cannot determine type of '_result' dtests/dtestlib/scales/TypeStrictComparator.py:29: error: Cannot determine type of '_result' dtests/dtestlib/scales/TypeStrictComparator.py:29: error: unused 'type: ignore' comment dtests/dtestlib/scales/DictComparator.py:34: error: Incompatible types in assignment (expression has type "Dict[<nothing>, <nothing>]", variable has type "List[Any]") dtests/dtestlib/scales/DictComparator.py:53: error: Incompatible types in assignment (expression has type "None", variable has type "List[Any]") dtests/dtestlib/scales/DictComparator.py:33: error: unused 'type: ignore' comment dtests/dtestlib/scales/DictComparator.py:49: error: unused 'type: ignore' comment dtests/dtestlib/scales/RelaxedComparator.py:28: error: Cannot determine type of '_result' dtests/dtestlib/scales/RelaxedComparator.py:29: error: Cannot determine type of '_result' dtests/dtestlib/scales/RelaxedComparator.py:35: error: Redundant cast to "bool" dtests/dtestlib/scales/RelaxedComparator.py:29: error: unused 'type: ignore' comment
Hi, I'm running into an issue with typevars unifying into
object and therefore allowing incorrect code. Example:
T = TypeVar("T") class Field(Generic[T]): dtype: Type[T] default: T foo = Field(int, "asdf") # I expect this to fail, but instead it typechecks since foo is a Field[object]
I found this issue which seems similar but is closed: python/mypy#6559
Is what I'm looking for possible in mypy?
Optionalwhen the expression type is
None? I would be happy to write a PR.
nanas a replacement for None, as it is possible to accidentally produce a
nan, but it's still possible to get
nanfor example by calculating
inf - inf
I'm not sure -- it worked for me?
PS C:\Users\A5rocks\Documents\boto-test> python -m venv venv ... PS C:\Users\A5rocks\Documents\boto-test> .\venv\Scripts\activate ... (venv) PS C:\Users\A5rocks\Documents\boto-test> pip install mypy boto3-stubs boto3 ... <open editor and put my code for example.py into, well, example.py> (venv) PS C:\Users\A5rocks\Documents\boto-test> mypy example.py example.py:3: note: Revealed type is 'def (self: boto3.NullHandler, record: Any) -> Any'
import boto3 reveal_type(boto3.NullHandler.emit)
(not sure if the
Anys were what you were talking about...)
I have encountered a strange behavior with
any(). This is a simplified example:
import typing T = typing.TypeVar('T') def children(_: T) -> typing.Iterable[T]: return  def orig(node: str) -> typing.Optional[str]: return any(orig(child) for child in children(node)) def no_errors(node: int) -> typing.Optional[int]: return any(no_errors(child) for child in children(node))
this is the output of mypy:
$ mypy mypyany.py mypyany.py:6: error: Incompatible return value type (got "bool", expected "Optional[str]") Found 1 error in 1 file (checked 1 source file) $
I don't get the error in the
orig() function (I can "suppose" is because
any() is "too dynamic" returning the first element of a sequence of anything). But, I don't get why, just changing the return annotation type (as in
no_errors) the error goes away!
def my_decorator(f: Callable[..., T]) -> Callable[..., Container[T]]:...
mypygot released and now I'm getting errors about missing imports. Something changed about configuration file I think. I have everything in
setup.cfgand now suddenly it started ignoring configuration options. Can anyone point me on the right direction to fix this?
I've got a small question / problem about the inferred type with covariant generic types.
Iterable as an example, AFAIU
Iterable[B] is a subtype of
B is a subtype of
However the following doesn't make sense to me:
from typing import Iterable class Base: pass class A(Base): pass class B(Base): pass reveal_type([A(), B()]) # builtins.list[snippet.Base*] a_it: Iterable[A] = [A()] b_it: Iterable[B] = [B()] reveal_type([a_it, b_it]) # builtins.list[builtins.object*]
Iterable[B] are subtypes of
Iterable[Base], I'd expect the last result to be a
list[Iterable[Base]], however mypy finds
Am I wrong in my understanding?
I want to use
mypy as some sort of type-suggestion engine. Like https://pyre-check.org/docs/querying-pyre
Let's say I have this code:
def some(a: int) -> int: b = 1 return a + b
mypy query some will return
mypy query some.b will return
Is there any possible solution? Including very durty ones.
I've noticed that this is flagged in MyPy:
signature = inspect.signature(f) signature = signature.replace(parameters=params) f.__signature__ = signature
.../sig_tools.py:40: error: "Callable[..., Any]" has no attribute "__signature__"
From PEP 362, setting a
__signature__ is clearly allowed:
Note that the Signature object is created in a lazy manner, and is not automatically cached. However, the user can manually cache a Signature by storing it in the
In fact, this is pretty much the example from that PEP for modifying a signature. Should that be an issue to raise with typeshed?
How would I write a Generic TypeVar? Basically, I’m wanting to write the following demo function (does not work, but hopefully you can see what I’m writing):
T = TypeVar(“T”, bound=Hashable) V = TypeVar(“V”, bound=Hashable) M = TypeVar("M", bound=Mapping) def reverse_mapping(mydict: M[T, V]) -> M[V, T]: ...
But that’s wrong. I’d like to say my function takes a mapping, like OrderedDict, and it should be able to propogate that it will return a matching mapping, OrderedDict, but with the two type arguments reversed. I don’t critically need this, but it bothers me I don’t know how to write it.