Skip to content

Instantly share code, notes, and snippets.

@janaSunrise
Created March 13, 2022 06:28
Show Gist options
  • Save janaSunrise/62ef8a0611e68ead6062d0437164ec58 to your computer and use it in GitHub Desktop.
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.
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