Where communities thrive

  • Join over 1.5M+ people
  • Join over 100K+ communities
  • Free without limits
  • Create your own community
Repo info
    Bryan Forbes
    It’s not really clear in the mypy release note blog post
    Kyle Altendorf
    So is it just not possible?
    Kyle Altendorf
    @hauntsaninja should stubtest check the package and the stubs against each other when it comes to implicit optional hints? context is 9 messages up, but trio has a parameter =None and the stubs have : trio.abc.Clock = .... seems like it would be good to have some tool or another able to find this discrepancy.
    Is anyone here familiar with writting plugins for mypy?
    I'm trying to dynamically add a method to ca ClassDef in a plugin hook.
    What I can't work out is: how to construct new Function definitions.
    Because those function definitions need types in their args.
    But I don't know how to get arbitrary types
    I know this is a really dumb question, but how can I construct mypy.nodes.Var objects?
    And mypy.nodes.TypeInfo
    This message was deleted
    Sorry for thinking outloud
    I think lookup_fully_qualified is what I need.
    It'd be nice if there was autodocumentation for the plugin api
    6 replies
    Henry Schreiner
    :heart: MyPy 0.800 :heart:
    @freundTech thanks for your help. I've actually managed to do something pretty cool with it.
    Basically, I was getting really annoyed with how a lot of python web developers just do ad hoc interfaces between services. And I wanted to see if I could create a metaprogrammed OpenAPI client; but one where I could also use MyPy to verify you are using the API correctly.
    @bryanforbes agreed that the blog post is a little confusingly worded. PEP 484 was amended to say that only import X as X counts as an explicit re-export, not import X as Y. What happens in regular .py files depends on whether or not you have --implicit-reexport or not
    Bryan Forbes
    Thanks! If the import X as X is included in __all__ in a regular .py file, will it be exported?
    yeah, symbols in __all__ should be exported
    @altendky stubtest does check that default values are a subtype of the arg's type hint
    maybe the issue is that your stub is decorated?
    Bryan Forbes
    @hauntsaninja thanks!
    Kyle Altendorf
    @hauntsaninja the stub uses ... for the default. it seems like the package default isn't checked against the stub hint. or at least isn't enforcing no implicit optional
    @altendky can you remove the decorator and try?
    Kyle Altendorf
    @hauntsaninja i tried removing it and it didn't seem to make a difference. it sounds like you expect it ought to be caught so i'll make up a minimal example to try to confirm expectations and outcome. thanks.
    Kyle Altendorf
    @hauntsaninja https://gist.github.com/altendky/3327ab219a04e27f628b92aa6c480d8a here's the minimal example. i can certainly file a ticket if you think it is appropriate.
    also, this isn't a pressing issue. at this point i'm starting to just merge the stubs into the package so this is relevant primarily in the context of just improving (i think? :]) stubtest.
    @altendky if i change your repro to create a pyi file instead of a py file in package-stubs, i get:
    error: package.f is inconsistent, runtime argument "p" has a default value of type None, which is incompatible with stub argument type builtins.int
    Stub: at line 1
    def (p: builtins.int =)
    Runtime: at line 1 in file /Users/shantanu/tmp/lol/package/__init__.py
    def (p=None)
    altendky @altendky sighs
    Kyle Altendorf
    bad repro, sorry.
    i'll explore the difference between that and the actual situation. thanks.
    thanks for making a repro though! :-) let me know if there's something i could add to stubtest to make debugging easier
    Hi, can anyone help me understand what is wrong with my annotations on my code https://bpa.st/MGSOM . mypy thinks there is an error on L8 but I dont understand what is wrong. It looks like mypy correctly restricts to one type of a Union when it enters an if block but it throws that knowledge away when it enters a locally defined function (compare L5 & L7). Is this a mypy bug?
    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)
    Hi There! How can we use an if statement in a for loop statement?
    Anyone please
    Alex Grönholm
    @Jahnavi-Jonnalagadda please elaborate?
    Amndeep Singh Mann
    Hi folks, like was stated in the documentation, I'm trying to manually go over the stub file created by stubgen so as to provide explicit types where possible instead of using Any. I'm currently running into a snag where I don't know how to deal with a NewType that 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 Any?
    # test.py
    from dataclasses import dataclass
    from typing import NewType
    A = NewType("A", str)
    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
    Johannes Bechberger
    Has anyone experiences with supervising a thesis that has a student working on mypy? I'm going to supervise a bachelors thesis starting in April that is focused on analysing the exhaustiveness of structural pattern matching in mypy (https://pp.ipd.kit.edu/thesis.php?id=323&lang=en), as a colleague of mine developed such an analysis for Haskell.
    Jiri Daněk
    Any advice about dmypy and mypy giving different results when checking the same code?
    % 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?

    5 replies
    Jon Shea
    A coworker of mine just asked “Is there a preferred way to return a non-value (null) from a function returning floats? Type checking doesnt like None being returned when the type is float.” Have we thought about having the “Incompatible types in assignment” error message suggest using Optional when the expression type is None? I would be happy to write a PR.
    Kyle Altendorf
    i'd be wondering about an exception... but NaN is the float non-value i'd think. optional returns are a bit annoying as every call site has to check for none-ness if it does anything but pass-through the value.
    Adrian Freund
    I personally wouldn't return nan as a replacement for None, as it is possible to accidentally produce a nan value.
    Python is more resistant to this than other languages, as division by 0 raises an Error instead of returning inf or nan, but it's still possible to get nan for example by calculating inf - inf
    Jon Shea
    I should have clarified, but I presupposed that Optional[int] is indeed the best choice for my coworker, and is likely to be the best choice for most users who end up running into the error: Incompatible types in assignment (expression has type "None", variable has type "foo").
    Tanner Stirrat
    i'm using mypy and i've got an error that seems to be something to the effect of "Argument 2 to foo has incompatible type B; expected Union[A, B, C, D]"
    there's a possibility that the B that I think I've given it and the B that it received aren't the same - i can check that - but is the above a known failure mode? if so, what does it indicate?