Where communities thrive


  • Join over 1.5M+ people
  • Join over 100K+ communities
  • Free without limits
  • Create your own community
People
Repo info
Activity
    Housa Hitomi
    @TWT233
    Hi dears, I wonder if typing supports var length param,
    pseudo code and ques:
    from typing import Any
    
    
    def one_param(a: int, b: Any):
        ...
    
    
    def two_param(a: int, b: Any, c: Any):
        ...
    
    # there are three, four and more
    # is there a typing hint matches all types
    # such as 'Callable[[int, *Any], None]'(in my intuitive opinion)?
    1 reply
    Tyler Yep
    @TylerYep
    Does mypy have a release schedule? There's a few Python 3.10 features I want to use, like @dataclass(slots=True), but blocked on using these until the next release (I generally prefer not using latest)
    mcepl
    @mcepl:matrix.org
    [m]
    Is there some way how to say that all children of one module (C-extension module in my case) is of type Any and not bother with it? When running mypy on M2Crypto I get 934 mostly false positive errors which makes mypy useless.
    layday
    @layday:matrix.org
    [m]
    [[tool.mypy.overrides]]
    module = "<untyped-module>.*"
    ignore_missing_imports = true
    Adrian Garcia Badaracco
    @adriangb
    Does anyone know how to get this example working?
    https://mypy-play.net/?mypy=latest&python=3.10&gist=ec78c8c7e92f87321c92a08927b795db
    import typing
    
    T = typing.TypeVar("T")
    
    def f(
        tp: typing.Type[T],
        inst: T,
    ) -> T:
        """inst must be an instance of a subtype of tp
        NOT tp must be a subtype of inst's type
        """
    
    class A:
        ...
    
    class B(A):
        ...
    
    class C:
        ...
    
    f(A, B())  # should work
    f(A, C())  # should fail
    7 replies
    Adrian Garcia Badaracco
    @adriangb
    I'm trying to make a return type that can carry some metadata along w/ the actual type being returned. This seems like a logical use for Annotated, but it comes out to be super verbose. Is there any way to make this cleaner?
    from typing import Annotated, Any, NamedTuple
    
    # We want to allow the user to add some metadata to the return type
    # The simplest way is two have two classes, one for the type, one for the metadata
    
    class Marker(NamedTuple):
        num: int
        string: str
    
    class A:
        ...
    
    def f1() -> Annotated[A, Marker(200, "hello")]:
        ...
    
    # This is very verbose, ideally I would like to be able to do something like
    
    class B:
        def __class_getitem__(cls, params: tuple[int, str]) -> Any:
            return Annotated[cls, Marker(*params)]
    
    def f2() -> B[200, "hello"]:  # errors
        ...
    Francisco Boni
    @insilications

    I'm having the same problem as described here: mypyc/mypyc#838
    @JelleZijlstra says that "This would be fixable by adding text_signature attribute to the compiled function object"

    Is there a way to do that in a dynamic fashion, perhaps with the help of mypy?

    JichangJang
    @jangjichang
    def bind(self, field_name: str, parent: Serializer) -> None:
        if self.method_name is None:
            self.method_name = "get_{field_name}".format(field_name=field_name)
        super().bind(field_name, parent)

    Even if there is no return value of the function, do i have to make an annotation?

    I use 'mypy', but if there is no annotation, the following error occurs. How can I ignore this error?

    error: Function is missing a return type annotation

    I want to ignore the error only in the case of 'return none'.

    2 replies
    Christoph Blessing
    @cblessing24

    Is it possible to ignore errors that are not associated with a particular line without disabling all checking for the file or globally disabling the error code?
    I have the following errors:

    repro/model/record.py:355: error: You may not have a custom __le__ method when order=True
    repro/model/record.py:356: error: You may not have a custom __lt__ method when order=True
    repro/model/record.py:357: error: You may not have a custom __gt__ method when order=True
    repro/model/record.py:358: error: You may not have a custom __ge__ method when order=True

    These errors seem to be false-positive and therefore I would like to ignore them but I can't do that because they aren't associated with a particular line for some reason. The line numbers in the error messages are incorrect. The file only has 140 lines. Any ideas?

    Orpheus
    @o:matrix.orpheuslummis.info
    [m]
    Does anyone know of formal comparisons between type systems?
    Darren Weston
    @darrenweston
    Is this a bug?
    class Cow:
        def test(self, d: int) -> Tuple[int, int]:
            return d+10, d+11
    
    
    def go():
        d = Cow()
        a, b = d.test("d") # <------ Why is this allowed?
    Alex Grönholm
    @agronholm
    @darrenweston seems like you forgot to annotate that go() function so it's not type checked
    1 reply
    Nicholas Grisafi
    @njgrisafi

    Curious if there's a way to lookup a NameExpr to get an associated AssignmentStmt in a mypy plugin? For example:

    # a.py
    vars = ["a"]

    We want lookup the fullname a.vars to get AssignmentExpr node for processing.

    1 reply
    Joshua Oreman
    @oremanj
    What is the relationship between mypy releases and typeshed? mypy 0.910 (released June 22) appears to contain a typeshed from before this change python/typeshed@f0bf6ee (committed May 17)
    Shantanu
    @hauntsaninja
    @oremanj that's expected. mypy vendors a copy of typeshed that is updated every now and then. recently, mypy releases have taken a long time, so the release branch has ended up getting cut fairly well before the actual release date.
    Joshua Oreman
    @oremanj
    @hauntsaninja thanks for clarifying -- is there any way to update typeshed independently of mypy?
    6 replies
    TDV Alinsa
    @alinsavix

    Hiiiii gang. I have a question regarding how to annotate, er... I guess you could call it dynamic attributes, but only kinda dynamic?

    Basically, I'm trying to get type hints working usefully for blender code, which is surprisingly challenging, but I've got it mostly behaving at this point! But there's one place where things are kind of obnoxious. Blender has standard types for things like scenes (bpy.types.Scene), and one of the things blender lets you do in an addon is add additional properties for your addon specifically -- basically just an attribute. So MyAddon can declare a MyAddonProperties class, and then have blender attach that to the scene type as bpy.types.Scene.MyAddon. And python typing, of course, doesn't know what the type of bpy.types.Scene.MyAddon is, because it doesn't exist until the addon manifests it into existence.

    So from one perspective, the bpy.types.Scene.MyAddon type is dynamic, in that it doesn't exist until code actually runs and creates it. But from another perspective, it's not really -- that particular attribute will always have the same type, if it exists, because my chunk of code (the addon) basically creates and treats it like a static attribute of the Scene class.

    The type is definitely known statically, and if it was just one big happy codebase I'd just go add a MyAddon: MyAddonProperties annotation in the bpy.types.Scene class and call it done. But my addon doesn't really "own" the base blender classes, and that would mean I'd need to start maintaining a copy of (some of) the blender type annotations myself, independently for every addon I'm working with, and that seems ... not ideal. I'd be totally happy to be able to drop a bpy.types.Scene.MyAddon: MyAddonProperties annotation in my code, but if I do that, it makes things complain because that annotation should be part of the type hints for bpy.types.Scene rather than existing in my code.

    As a workaround, at the moment I'm doing cast(MyAddon, whatever.things.scene.MyAddon) to force the type whenever I access that custom attribute, but that's a lot of visual clutter. Am I missing other options here, or am I pretty much boned on somehow being able to do this cleanly?

    15 replies
    [apologies for wall of text]
    lyz-code
    @lyz-code

    Hi all, I want to type a function that accepts an argument with two possible types, and returns a modified version of that argument.

    def func(content: Content) -> Content:
      ...

    How do I define the type hints so that if the argument is of the first type, the output type is of that same type?

    If I define Content as Union[str, int], it doesn't matter if you input an int or a str, the output is read as the Union.

    If I define Content as TypeVar('Content', str, int), I get a mypy error Type variable "Content" is unbound [valid-type].

    What I'm doing wrong?

    Thanks!

    12 replies
    dmr
    @dmrobertson:matrix.org
    [m]

    I'm not quite sure. I think the idea is to be explicit about type parameters so that the type system knows the different ways we can create a file.

    class File: ... is one concrete type, meant to be fully formed and entirely unambiguous.

    class File[Content]: ... is almost a "recipe" for creating different concrete types: File[str] and File[int] in this example.

    Christoph Blessing
    @cblessing24
    Hi all, how can I specify a TypeVar only for sub-classes of a certain class that implement a certain protocol?
    4 replies
    Adrian Garcia Badaracco
    @adriangb
    Is there any way to tell MyPy to type check a class like if it was inheriting from a Protocol, without actually inheriting from the Protocol? Something like:
    class SomeProtocol(Protocol):
        def func(self) -> None:
            ...
    
    class MyClass:  # type: SomeProtocol
        def func(self) -> int:  # I want an error here, incompatible return type
            ...
    6 replies
    The main reason I inherit from a Protocol is to make sure I implement it correctly. But that can be done statically by MyPy, (for this use case) there is no reason to actually inherit from the Protocol.
    Dhruv Soni
    @quickcodes
    Hello,
    Dhruv Soni
    @quickcodes
    Hello all, I am new to open source contribution and i am well aware of python and c++. I would love to contribute to mypy, could someone please guide me how can i get started.
    Gabriele Lanaro
    @gabrielelanaro

    Hello everyone, I have a question regarding an issue that I'm having when trying to implement a feature similar to elementwise addition to a sequence in a generic way. Is this a bug or I'm doing something incorrectly? The idea is as follows

    seq = MySequence([1, 2, 3])
    seq_plus_one = seq + 1
    # seq_plus_one is now [2, 3, 4]

    I attempted to type this sequence in a generic way using Protocol, but I'm stumbling on an error that seems to be incorrect (another typechecker -- pyright consider the following valid)

    from typing import Generic, Sequence, TypeVar, Protocol
    
    RightOp = TypeVar("RightOp", contravariant=True)
    Out = TypeVar("Out", covariant=True)
    
    
    class SupportsAdd(Protocol[RightOp, Out]):
        def __add__(self, other: RightOp) -> Out:
            ...
    
    
    Item = TypeVar("Item")
    G = TypeVar("G")
    F = TypeVar("F")
    
    
    class MySequence(Generic[Item]):
        def __init__(self, val: Sequence[Item]):
            self.val = val
    
        def __add__(self: "MySequence[SupportsAdd[G, F]]", other: G) -> "MySequence[F]":
            return MySequence([v + other for v in self.val])
    
    
    seq = MySequence([1, 2, 3])
    
    seq_plus_one = seq + 1
    reveal_type(seq)

    If I run mypy 0.910 on Python 3.10.0 I obtain Unsupported operand time which seems to be incorrect:

    examples/example2.py:27: error: Unsupported operand types for + ("MySequence[int]" and "int")
    examples/example2.py:28: note: Revealed type is "example2.MySequence[builtins.int*]"
    Found 1 error in 1 file (checked 1 source file)
    1 reply
    Anmol Raj Soni
    @anmolrajsoni15
    Hello everyone 👋🏻. I am a new comer to github. I want to contribute in mypy. I know Python, C, and C++. Please guide me to get started.
    Chris Wesseling
    @ccw:matrix.cwi.nl
    [m]
    Hi, I tried using typing_extenstins.Self from typing_extension 4.0.0 on cpython 3.8 like this: items: typing.List[typing_extensions.Self] but that threw a TypeError. I asked on StackOverflow and someone thought it might be a bug. I thought I'd ask here before poluting the issue tracker.
    Kritzefitz
    @kritzefitz:weltraumschlangen.de
    [m]
    Soll ich Döner oder Dönerbos mitbringen?
    1 reply
    Kritzefitz
    @kritzefitz:weltraumschlangen.de
    [m]
    Oops, wrong channel.
    Chris Wesseling
    @ccw:matrix.cwi.nl
    [m]
    Smecklich mahlzeit :)
    Noah Pederson
    @chiefnoah
    Hello, has anyone done any work with PEP 593/typing.Annotated? I'm struggling to find examples or documentation to work from
    2 replies
    Thijs Miedema
    @thijsmie
    Hi all, I'm having some trouble with typing class decorators that only support specific subclasses. I can TypeVar('T') def a(b: Type[T]) -> Type[T]: but then it is unrestricted. I can bind it to the parent TypeVar('T', ParentA, ParentB); def a(b: Type[T]) -> Type[T]: but then my IDE loses the specific subclass and the resultant type is just the parent. Am I missing something?
    Kaleb Barrett
    @ktbarrett

    @thijsmie you need to use bound and a Union

    T = TypeVar("T", bound=Union[ParentA, ParentB])

    This is saying that T can be ParentA, ParentB, or any subclasses of those two types. When you list the types like you did, the TypeVar matches only the exact classes specified, and not subtypes.

    1 reply
    Randolf Scholz
    @randolf-scholz
    Hey I have a question regarding type narrowing when subtypes are involved: The following code does not work, and I am wondering if this is a bug that I should open on issue. Currently, I can work around it by either adding a superfluous isinstance check or by type: ignore
    1 reply
    from collections.abc import Collection, Mapping
    
    def f(x: int | Collection[int] | Mapping[str, int]) -> int:
        r"""Recursively sum up all the values of possibly nested data."""
        if isinstance(x, int):
            return x
        if isinstance(x, Mapping):
            return sum(f(y) for y in x.values())
    
        reveal_type(x)   # <- Here, mypy thinks this is Collection only!
        if isinstance(x, Collection):
            reveal_type(x)  # <- Suddenly mypy thinks this is Collection | Mapping
            return sum(f(y) for y in x)
    
        raise TypeError(f"unsupported type: {type(x)}")
    Randolf Scholz
    @randolf-scholz
    ok I opened an issue anyway python/mypy#11615
    oh sorry, I see: by line 10, we'll have returned if we're an int or a Mapping. Good spot!
    cherrry9
    @cherrry9
    class Foo:
        @classmethod
        @property
        def bar(cls) -> str:
            return cls.__name__
    
    
    def foo_bar(msg: str) -> None:
        print(msg)
    
    foo_bar(Foo.bar)
    7 replies
    test.py:13: error: Argument 1 to "foo_bar" has incompatible type "Callable[[], str]"; expected "str"
    Found 1 error in 1 file (checked 1 source file)
    Is this intentent behavior? If so why mypy recognize classmethod property as callable
    parthaxntn
    @parthaxntn
    hello friends!
    I was using mypy and i found an issue. I feel mypy could not detect data-type of an empty variable.
    So, I felt like I could contribute by solving this issue. Can anyone help me to locate where the code for these part is situated among the folders and files.
    parthaxntn
    @parthaxntn
    e.g: a = [] or b = {} throws an error asking for type annotation.
    1 reply
    cherrry9
    @cherrry9
    def max_sum(it: Iterable[float]) -> float:
        """Return the maximum sum of a contiguous subsequence 
    
        >>> max_sum([5, -7, 3, 5, -2, 4, -1]) # max sum subsequence is [3, 5, -2, 4]
        10
    
        """
        prev = 0
        return max((prev := max(prev + v, v) for v in it))
    >>> mypy algo.py
    algo.py:107: error: Name "prev" already defined on line 106
    Found 1 error in 1 file (checked 1 source file)
    any idea why mypy is complaining and how to fix it?
    1 reply
    Rohit Rajvaidya
    @Rohitcode25
    I want to contribute and I am beginner how can I start?
    1 reply
    Amin Alaee
    @aminalaee

    Hello people, I'm just curious, why doesn't mypy complain about this:

    import typing
    
    def a(**kwargs: int):
        print(kwargs)
    
    
    def b(**kwargs: typing.Any):
        a(**kwargs)
    
    
    b(s="2")

    Here b is passing Any to a which could be anything beside int
    And it's not only the **kwargs, single variables behave the same.

    10 replies
    EXPLOSION
    @A5rocks

    I suppose I can ask here about how exactly to fix something in mypy? I was looking into python/mypy#11605 and found that this is because T and V have the same TypeVarId :S

    How can I fix this? I note that TypeVarId is only set in TypeVarScope.bind_new(), which itself starts the ids based on the parent. I then noticed that parent in this case was the file -- aha! But... I'm unsure how to set the parent to be the base class in visit_class_def in semanal.py, due to two issues:

    • not sure how to access the base class(es)
    • TypeVarScope seems like it would have to support multiple parents (multiple inheritence + need the function scope that the class is in) -- I implemented this before realizing the first point existed and I had no clue how to continue.