Skip to content

Instantly share code, notes, and snippets.

@SF-300
Last active March 23, 2023 11:06
Show Gist options
  • Save SF-300/1be681b3536271a8571866499cf132b1 to your computer and use it in GitHub Desktop.
Save SF-300/1be681b3536271a8571866499cf132b1 to your computer and use it in GitHub Desktop.
More convenient syntax for SimpleNamespace instances creation.
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