Question Details

No question body available.

Tags

python python-typing typing

Answers (2)

Accepted Answer Available
Accepted Answer
February 13, 2026 Score: 6 Rep: 92 Quality: Expert Completeness: 100%

Use typing.cast when the runtime subtype is known

If you are certain that someobject.method() will always return B in your specific context, the idiomatic way to inform the type checker without using assert is typing.cast.

cast is a static typing construct: it affects only the type checker and has no effect at runtime.

from typing import cast

class MyClass: def init(self): variable = cast(B, someobject.method()) self.attribute = variable

This tells tools like mypy or pyright to treat the value as B, even though the declared return type is A.

When to use this

  • Use assert isinstance(...) if you want a runtime check.

  • Use cast(...) if the subtype is guaranteed by external logic and you only need to narrow the type for static analysis.

cast is appropriate here because the type narrowing is based on contextual knowledge that the type checker cannot infer.

February 13, 2026 Score: -4 Rep: 99 Quality: Low Completeness: 80%

It depends on whether you are trying to hint an instance of a subclass or the class object itself.

Scenario 1: You want to accept the Class itself (The Factory Pattern)

If you want to pass the class Dog (the blueprint) to a function, use type[T].

  • Modern Python (3.9+): Use the built-in type[].

  • Older Python: Use typing.Type[].

Python

class Animal: ...
class Dog(Animal): ...

Accepts the CLASS 'Dog', not an instance like 'Dog()'

def makeanimal(animalclass: type[Animal]) -> Animal: return animalclass()

makeanimal(Dog) # Valid makeanimal(Animal) # Valid makeanimal(str) # Error: 'str' is not a subtype of 'Animal'


### Scenario 2: You want the return type to match the input type

If you want your function to return the exact subclass that was passed in (e.g., if I pass Dog, I get back Dog, not just Animal), you need a TypeVar bound to the parent class.

Python

from typing import TypeVar

T must be a subclass of Animal

T = TypeVar("T", bound="Animal")

def createinstance(cls: type[T]) -> T: return cls()

dog = createinstance(Dog)

Type Checker knows 'dog' is of type 'Dog', not just 'Animal'


### Scenario 3: You just mean an instance

If you just want to accept an object that is a subclass of Animal, you don't need special syntax. Standard hints are covariant by default.

Python

# Accepts instance of Animal OR Dog OR Cat
def petanimal(pet: Animal):
    pass

petanimal(Dog()) # Valid