Skip to content

Instantly share code, notes, and snippets.

@ambv
Last active September 21, 2021 17:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ambv/0ed9c9ec5b8469878f47074bdcd37b0c to your computer and use it in GitHub Desktop.
Save ambv/0ed9c9ec5b8469878f47074bdcd37b0c to your computer and use it in GitHub Desktop.
Should `__init__()` be part of a protocol?
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