In Python type annotations, is there some way to declare that a property has the same type as a property of another class? To “borrow” or copy the type from the other class?
For example, in this code, how could you say that bar
should have the same type as the foo
property of a Foo
class instance?
# Python
from some_library import Foo # class Foo
class Bar(Foo):
bar: ??? typeof Foo.foo ??? # what goes here?
I’m looking for the equivalent of this TypeScript:
// TypeScript
import { Foo } from "some_library"; // class Foo
class Bar extends Foo {
bar: Foo["foo"]; // bar has same type as `new Foo().foo`
}
More info: Foo
is defined in type stubs that are not under my control. I’m looking for a solution that doesn’t involve modifying third-party code or importing its private underscore types.
# some_library.pyi
from typing import TypedDict
class _FooErrorTypeDef(TypedDict, total=False):
message: str
severity: str
class _FooPropTypeDef(TypedDict, total=False):
status: str
code: str | number
errors: list[_FooErrorTypeDef] | None
class Foo:
def __init__(self):
self.foo: _FooPropTypeDef
7