Where communities thrive

  • Join over 1.5M+ people
  • Join over 100K+ communities
  • Free without limits
  • Create your own community
Repo info
    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?
    @tstirrat15 : why don't you reveal_type(foo) to see the full type info
    Tanner Stirrat
    @silviogutierrez does reveal_type work when mypy is running or when you run the code? I can't tell from the cheatsheet
    nvm got it
    it's mypy
    Tanner Stirrat
    it looks like a restatement of the B type. it's not given in the same syntax.
    Daniel Eloff
    How does one install library stubs for mypy? I tried just installed boto3-stubs, but mypy still complains boto3 doesn't have any typings. How could I check if mypy is finding it or not? Details here: https://stackoverflow.com/questions/65894133/mypy-not-picking-up-installed-stubs

    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

    (not sure if the Anys were what you were talking about...)

    Vito De Tullio

    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!

    1 reply
    Sebastian Wagner
    hey folks, I'm a bit lost right now. anyone knows how to make a proper decorator that changes the generic return argument?, like