Last active
July 12, 2025 21:34
-
-
Save internetimagery/676dbc1d46fcd2c8656d072c07564247 to your computer and use it in GitHub Desktop.
Separate factory from class
This file contains hidden or 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
| import dataclasses | |
| class DataFactory(type): | |
| def from_number(cls, num: int) -> "Data": | |
| return cls(str(num)) | |
| @dataclasses.dataclass | |
| class Data(metaclass=DataFactory): | |
| value: str | |
| d = Data.from_number(123) # <-- Method only available on the class, not on the instance | |
| print(d) | |
| assert "from_number" not in dir(d) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment