Created
March 13, 2022 06:28
-
-
Save janaSunrise/62ef8a0611e68ead6062d0437164ec58 to your computer and use it in GitHub Desktop.
Ensuring the class implementing this metaclass has `from_dict` method, to load data from dictionary. This is usually common for dataclasses to load data into them and return an object of the class.
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
import typing as t | |
class FromDictMeta(type): | |
"""Metaclass to ensure inherited classes have `from_dict` class method.""" | |
def __new__( | |
cls, | |
name: str, | |
bases: t.Tuple[type, ...], | |
attrs: t.Dict[str, t.Any], | |
): | |
if "from_dict" not in attrs: | |
raise TypeError(f"{name} must implement `from_dict` class method.") | |
return super().__new__(cls, name, bases, attrs) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment