Created
January 31, 2024 12:19
-
-
Save qstokkink/9f853a8329966a266b90321414f15ab5 to your computer and use it in GitHub Desktop.
An Entity class to inherit from and bind later.
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 __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