简体   繁体   中英

How do you type-hint class prototypes that don't otherwise exist?

I have legacy code with inheriting dataclasses:

@dataclass
class Base:
    a: int

@dataclass
class Derived1(Base):
    b: int

@dataclass
class Derived2(Base):
    b: int

I want to use Python type hints so that methods know when they're getting something with a b attribute. However, I cannot import actual Derived1 or Derived2. So I want something like:

def uses_b(b_supporting_object: TIsBaseWithB):
    ...

How do you define a TIsBaseWithB ? Is NewType related?

Use typing.Protocol :

from typing import Protocol


class SupportsB(Protocol):
    b: int

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM