Python – Zugriff auf einen begrenzten generischen TyphinweisPython

Python-Programme
Anonymous
 Python – Zugriff auf einen begrenzten generischen Typhinweis

Post by Anonymous »

mypy ist mit dem folgenden Code unzufrieden, weil

Code: Select all

app.py:33: error: List comprehension has incompatible type List[TradeBar | QuoteBar]; expected List[T]  [misc]
Auch wenn wir wissen, dass dieser_Typ die Klasse ist, die T ist.
  • Warum ist Mypy unglücklich? Handelt es sich um eine nicht unterstützte Funktion oder mache ich etwas Dummes?
  • Wenn das albern ist, wie könnte ich das besser machen? Sollte ich nur BarBase als Typ-Obergrenze verwenden, d. h.
    ?

    Code: Select all

    class MyUsefulClass[T: BarBase]
    
Danke

Code: Select all

from datetime import datetime
from dataclasses import dataclass, asdict

@dataclass
class BarBase:
sym: str
timestamp: datetime | None

@dataclass
class TradeBar(BarBase):
open: float
high: float
low: float
close: float

@dataclass
class QuoteBar(BarBase):
bid: float
ask: float

Bars = TradeBar | QuoteBar

class MyUsefulClass[T: Bars]:
def __init__(self, this_type: type[T]):
self.this_type = this_type

def silly_fn(self, x: T, y: T) -> list[T]:
return [self.this_type(**asdict(a)) for a in (x, y)]

util = MyUsefulClass[QuoteBar](QuoteBar)

util.silly_fn(
QuoteBar(sym="abc", timestamp=None, bid=1.1, ask=2.2),
QuoteBar(sym="def", timestamp=None, bid=99.9, ask=100.1),
)

Quick Reply

Change Text Case: 
   
  • Similar Topics
    Replies
    Views
    Last post