Last active
March 23, 2023 11:06
-
-
Save SF-300/1be681b3536271a8571866499cf132b1 to your computer and use it in GitHub Desktop.
More convenient syntax for SimpleNamespace instances creation.
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 types import SimpleNamespace | |
from typing import Any | |
__all__ = "NamespaceMeta", "Namespace" | |
class NamespaceMeta(type): | |
"""Provides namespacing infrastructure. | |
This metaclass provides an alternative (and hopefully more convenient) syntax for creating 'types.SimpleNamespace' | |
instances using 'class' syntax. | |
>>> class Events(metaclass=NamespaceMeta): | |
... class A: | |
... f: int | |
... | |
... class B: | |
... f: str | |
>>> isinstance(Events, SimpleNamespace) | |
True | |
""" | |
def __new__(mcs, name: str, bases: tuple[type], namespace: dict[str, Any]): | |
if name == "Namespace" and namespace.get("__module__", None) == __name__: | |
return super().__new__(mcs, name, bases, namespace) | |
return SimpleNamespace(**namespace) | |
class Namespace(metaclass=NamespaceMeta): | |
pass |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment