-
Notifications
You must be signed in to change notification settings - Fork 2
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Loading status checks…
feat: added experimental init and annotation mixins
Showing
3 changed files
with
39 additions
and
1 deletion.
There are no files selected for viewing
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1 +1,2 @@ | ||
from .base import * # noqa | ||
from .mixins import * # noqa |
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
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,35 @@ | ||
from sqlalchemy import Column | ||
|
||
|
||
class AutoAnnotateMixin: | ||
@classmethod | ||
def __init_subclass__(cls) -> None: | ||
super().__init_subclass__() | ||
annotations = {} | ||
for key, value in cls.__dict__.items(): | ||
if isinstance(value, Column): | ||
annotations[key] = value.type.python_type | ||
cls.__annotations__ = annotations | ||
|
||
|
||
class AutoInitMixin: | ||
@classmethod | ||
def __init_subclass__(cls) -> None: | ||
super().__init_subclass__() | ||
init_params = [] | ||
for key, value in cls.__dict__.items(): | ||
if isinstance(value, Column): | ||
if not value.nullable and not value.default and not value.server_default: | ||
init_params.append((key, value.type.python_type)) | ||
|
||
def __init__(self, **kwargs): | ||
super(cls, self).__init__() | ||
for key, _ in init_params: | ||
if key not in kwargs: | ||
raise TypeError(f"Missing required argument: {key}") | ||
setattr(self, key, kwargs[key]) | ||
for key, value in kwargs.items(): | ||
if key not in init_params and hasattr(self.__class__, key): | ||
setattr(self, key, value) | ||
|
||
cls.__init__ = __init__ |