-
-
Notifications
You must be signed in to change notification settings - Fork 23
Expand file tree
/
Copy pathmodel.py
More file actions
99 lines (70 loc) · 2.46 KB
/
Copy pathmodel.py
File metadata and controls
99 lines (70 loc) · 2.46 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
import dataclasses
import log
from classproperties import classproperty
from . import config, hooks, settings
from .manager import Manager
from .mapper import Mapper, create_mapper
class Model:
Meta: config.Meta = config.Meta()
datafile: Mapper
def __post_init__(self):
log.debug(f"Initializing {self.__class__} object")
# Using object.__setattr__ in case of frozen dataclasses
object.__setattr__(self, "datafile", create_mapper(self))
if settings.HOOKS_ENABLED:
with hooks.disabled():
path = self.datafile.path
exists = self.datafile.exists
create = not self.datafile.manual
if path:
log.debug(f"Datafile path: {path}")
log.debug(f"Datafile exists: {exists}")
if exists:
self.datafile.load(_first_load=True)
elif path and create:
self.datafile.save()
hooks.apply(self, self.datafile)
log.debug(f"Initialized {self.__class__} object")
@classproperty
def objects(cls) -> Manager: # pylint: disable=no-self-argument
return Manager(cls)
def create_model(
cls,
*,
attrs=None,
manual=None,
pattern=None,
defaults=None,
infer=None,
rename=None,
):
"""Patch model attributes on to an existing dataclass."""
log.debug(f"Converting {cls} to a datafile model")
if not dataclasses.is_dataclass(cls):
raise ValueError(f"{cls} must be a dataclass")
# Patch meta
m = getattr(cls, "Meta", config.Meta())
if attrs is not None:
m.datafile_attrs = attrs
if pattern is not None:
m.datafile_pattern = pattern
if not hasattr(cls, "Meta") and manual is not None:
m.datafile_manual = manual
if not hasattr(cls, "Meta") and defaults is not None:
m.datafile_defaults = defaults
if not hasattr(cls, "Meta") and infer is not None:
m.datafile_infer = infer
if not hasattr(cls, "Meta") and rename is not None:
m.datafile_rename = rename
cls.Meta = m
# Patch manager
cls.objects = Manager(cls)
# Patch __init__
init = cls.__init__
def modified_init(self, *args, **kwargs):
with hooks.disabled():
init(self, *args, **kwargs)
Model.__post_init__(self)
cls.__init__ = modified_init
cls.__init__.__doc__ = init.__doc__
return cls