Skip to content

Instantly share code, notes, and snippets.

@qstokkink
Created January 31, 2024 12:19
Show Gist options
  • Save qstokkink/9f853a8329966a266b90321414f15ab5 to your computer and use it in GitHub Desktop.
Save qstokkink/9f853a8329966a266b90321414f15ab5 to your computer and use it in GitHub Desktop.
An Entity class to inherit from and bind later.
from __future__ import annotations
from typing import Type, TypeVar, cast
from pony.orm import Database
from pony.orm.core import EntityMeta # This is a "secret" import
class UnboundEntityMeta(EntityMeta):
"""
Inert form of EntityMeta.
"""
def __init__(self):
"""
Init? I think not!
"""
object.__init__(self)
def __new__(cls, *args, **kwargs):
"""
New? Rejected!
"""
return type(*args)
class Entity(metaclass=UnboundEntityMeta):
"""
An bind-able database entity.
"""
db: Database
@classmethod
def bind(cls: EntityImpl, database: Database) -> EntityImpl:
"""
Bind to a database instance.
"""
cls.db = database
return cast(EntityImpl, type(cls.__name__, (database.Entity, ), {**cls.__dict__}))
EntityImpl = TypeVar("EntityImpl", bound=Type[Entity])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment