-
-
Save ambv/0ed9c9ec5b8469878f47074bdcd37b0c to your computer and use it in GitHub Desktop.
Should `__init__()` be part of a protocol?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from dataclasses import dataclass | |
from typing import Protocol, Type | |
@dataclass | |
class Ball: | |
x: float | |
y: float | |
z: float | |
class Init(Protocol): | |
def __init__(self, ball: Ball) -> None: | |
... | |
def get_ball(self) -> Ball: | |
... | |
class BallContainer: | |
def __init__(self, ball: Ball) -> None: | |
self.ball = ball | |
def get_ball(self) -> Ball: | |
return self.ball | |
class TwoBallContainer: | |
def __init__(self, ball: Ball, ball2: Ball) -> None: | |
self.ball = ball | |
self.ball2 = ball2 | |
def get_ball(self) -> Ball: | |
return self.ball | |
def get_ball2(self) -> Ball: | |
return self.ball2 | |
def make(ball: Ball, container: Type[Init]) -> None: | |
c = container(ball) | |
print(c) | |
if __name__ == "__main__": | |
make(Ball(x=1, y=2, z=3), BallContainer) | |
make(Ball(x=1, y=2, z=3), TwoBallContainer) # <-- invalid but Mypy allows it | |
make(Ball(x=1, y=2, z=3), object) # <-- Mypy disallows it |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment