Skip to content

Default of TypeVar isn't respected for assignments. #18904

Closed as duplicate of#18812
@s3rius

Description

@s3rius

Hello, here's an issue I stumbled upon.

from typing import Generic, Type
from typing_extensions import TypeVar


class Interface: ...


_T = TypeVar("_T", bound=Interface, default=Interface)


class MyGeneric(Generic[_T]):
    def __init__(self) -> None:
        super().__init__()
        self._value: Type[_T] = Interface

In this example, I expect this code to be valid, because I have a default value for _T and don't have it in constructor.
Also, while playing around I noticed that default doesn't work with default argument in __init__ either.

from typing import Generic, Type
from typing_extensions import TypeVar


class Interface: ...


_T = TypeVar("_T", bound=Interface, default=Interface)


class MyGeneric(Generic[_T]):
    def __init__(self, my_val: Type[_T] = Interface) -> None:
        super().__init__()
        self._value = my_val

I'd expect this to be valid code because we define the default for the Type[_T] argument before the object is initialized, so it should fall back to the default of TypeVar in that case. At least, that's what I would expect.

Is this intended behavior?

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions