ducktools-classbuilder 0.7.0__py3-none-any.whl → 0.7.2__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of ducktools-classbuilder might be problematic. Click here for more details.

@@ -363,15 +363,17 @@ def eq_generator(cls, funcname="__eq__"):
363
363
  ]
364
364
 
365
365
  if field_names:
366
- selfvals = ",".join(f"self.{name}" for name in field_names)
367
- othervals = ",".join(f"other.{name}" for name in field_names)
368
- instance_comparison = f"({selfvals},) == ({othervals},)"
366
+ instance_comparison = "\n and ".join(
367
+ f"self.{name} == other.{name}" for name in field_names
368
+ )
369
369
  else:
370
370
  instance_comparison = "True"
371
371
 
372
372
  code = (
373
373
  f"def {funcname}(self, other):\n"
374
- f" return {instance_comparison} if {class_comparison} else NotImplemented\n"
374
+ f" return (\n"
375
+ f" {instance_comparison}\n"
376
+ f" ) if {class_comparison} else NotImplemented\n"
375
377
  )
376
378
  globs = {}
377
379
 
@@ -390,11 +392,13 @@ def frozen_setattr_generator(cls, funcname="__setattr__"):
390
392
  if flags.get("slotted", True):
391
393
  globs["__setattr_func"] = object.__setattr__
392
394
  setattr_method = "__setattr_func(self, name, value)"
395
+ hasattr_check = "hasattr(self, name)"
393
396
  else:
394
397
  setattr_method = "self.__dict__[name] = value"
398
+ hasattr_check = "name in self.__dict__"
395
399
 
396
400
  body = (
397
- f" if hasattr(self, name) or name not in __field_names:\n"
401
+ f" if {hasattr_check} or name not in __field_names:\n"
398
402
  f' raise TypeError(\n'
399
403
  f' f"{{type(self).__name__!r}} object does not support "'
400
404
  f' f"attribute assignment"\n'
@@ -707,10 +711,6 @@ def make_slot_gatherer(field_type=Field):
707
711
  "in order to generate a slotclass"
708
712
  )
709
713
 
710
- # Don't want to mutate original annotations so make a copy if it exists
711
- # Looking at the dict is a Python3.9 or earlier requirement
712
- cls_annotations = get_ns_annotations(cls_dict)
713
-
714
714
  cls_fields = {}
715
715
  slot_replacement = {}
716
716
 
@@ -724,8 +724,6 @@ def make_slot_gatherer(field_type=Field):
724
724
 
725
725
  if isinstance(v, field_type):
726
726
  attrib = v
727
- if attrib.type is not NOTHING:
728
- cls_annotations[k] = attrib.type
729
727
  else:
730
728
  # Plain values treated as defaults
731
729
  attrib = field_type(default=v)
@@ -738,7 +736,6 @@ def make_slot_gatherer(field_type=Field):
738
736
  # In this case, slots with documentation and new annotations.
739
737
  modifications = {
740
738
  "__slots__": slot_replacement,
741
- "__annotations__": cls_annotations,
742
739
  }
743
740
 
744
741
  return cls_fields, modifications
@@ -748,7 +745,7 @@ def make_slot_gatherer(field_type=Field):
748
745
 
749
746
  def make_annotation_gatherer(
750
747
  field_type=Field,
751
- leave_default_values=True,
748
+ leave_default_values=False,
752
749
  ):
753
750
  """
754
751
  Create a new annotation gatherer that will work with `Field` instances
@@ -814,7 +811,7 @@ def make_annotation_gatherer(
814
811
 
815
812
  def make_field_gatherer(
816
813
  field_type=Field,
817
- leave_default_values=True,
814
+ leave_default_values=False,
818
815
  ):
819
816
  def field_attribute_gatherer(cls_or_ns):
820
817
  if isinstance(cls_or_ns, (_MappingProxyType, dict)):
@@ -847,7 +844,7 @@ def make_field_gatherer(
847
844
 
848
845
  def make_unified_gatherer(
849
846
  field_type=Field,
850
- leave_default_values=True,
847
+ leave_default_values=False,
851
848
  ):
852
849
  """
853
850
  Create a gatherer that will work via first slots, then
@@ -897,7 +894,7 @@ annotation_gatherer = make_annotation_gatherer()
897
894
 
898
895
  # The unified gatherer used for slot classes must remove default
899
896
  # values for slots to work correctly.
900
- unified_gatherer = make_unified_gatherer(leave_default_values=False)
897
+ unified_gatherer = make_unified_gatherer()
901
898
 
902
899
 
903
900
  # Now the gatherers have been defined, add __repr__ and __eq__ to Field.
@@ -963,7 +960,7 @@ class AnnotationClass(metaclass=SlotMakerMeta):
963
960
  def __init_subclass__(
964
961
  cls,
965
962
  methods=default_methods,
966
- gatherer=make_unified_gatherer(leave_default_values=True),
963
+ gatherer=unified_gatherer,
967
964
  **kwargs
968
965
  ):
969
966
  # Check class dict otherwise this will always be True as this base
@@ -178,37 +178,37 @@ def make_slot_gatherer(
178
178
  @typing.overload
179
179
  def make_annotation_gatherer(
180
180
  field_type: type[_FieldType],
181
- leave_default_values: bool = True,
181
+ leave_default_values: bool = False,
182
182
  ) -> Callable[[type | _CopiableMappings], tuple[dict[str, _FieldType], dict[str, typing.Any]]]: ...
183
183
 
184
184
  @typing.overload
185
185
  def make_annotation_gatherer(
186
186
  field_type: _ReturnsField = Field,
187
- leave_default_values: bool = True,
187
+ leave_default_values: bool = False,
188
188
  ) -> Callable[[type | _CopiableMappings], tuple[dict[str, Field], dict[str, typing.Any]]]: ...
189
189
 
190
190
  @typing.overload
191
191
  def make_field_gatherer(
192
192
  field_type: type[_FieldType],
193
- leave_default_values: bool = True,
193
+ leave_default_values: bool = False,
194
194
  ) -> Callable[[type | _CopiableMappings], tuple[dict[str, _FieldType], dict[str, typing.Any]]]: ...
195
195
 
196
196
  @typing.overload
197
197
  def make_field_gatherer(
198
198
  field_type: _ReturnsField = Field,
199
- leave_default_values: bool = True,
199
+ leave_default_values: bool = False,
200
200
  ) -> Callable[[type | _CopiableMappings], tuple[dict[str, Field], dict[str, typing.Any]]]: ...
201
201
 
202
202
  @typing.overload
203
203
  def make_unified_gatherer(
204
204
  field_type: type[_FieldType],
205
- leave_default_values: bool = True,
205
+ leave_default_values: bool = False,
206
206
  ) -> Callable[[type | _CopiableMappings], tuple[dict[str, _FieldType], dict[str, typing.Any]]]: ...
207
207
 
208
208
  @typing.overload
209
209
  def make_unified_gatherer(
210
210
  field_type: _ReturnsField = Field,
211
- leave_default_values: bool = True,
211
+ leave_default_values: bool = False,
212
212
  ) -> Callable[[type | _CopiableMappings], tuple[dict[str, Field], dict[str, typing.Any]]]: ...
213
213
 
214
214
 
@@ -249,7 +249,7 @@ class AnnotationClass(metaclass=SlotMakerMeta):
249
249
  def __init_subclass__(
250
250
  cls,
251
251
  methods: frozenset[MethodMaker] | set[MethodMaker] = default_methods,
252
- gatherer: _gatherer_type = make_unified_gatherer(leave_default_values=True),
252
+ gatherer: _gatherer_type = unified_gatherer,
253
253
  **kwargs,
254
254
  ) -> None: ...
255
255
 
@@ -1,2 +1,2 @@
1
- __version__ = "0.7.0"
2
- __version_tuple__ = (0, 7, 0)
1
+ __version__ = "0.7.2"
2
+ __version_tuple__ = (0, 7, 2)
@@ -24,6 +24,19 @@ import sys
24
24
  import builtins
25
25
 
26
26
 
27
+ # Evil stuff from types.py
28
+ def _cell_factory():
29
+ a = 1
30
+
31
+ def f():
32
+ nonlocal a
33
+ return f.__closure__[0]
34
+ _FunctionType = type(_cell_factory)
35
+ _CellType = type(_cell_factory())
36
+ del _cell_factory
37
+ # End evil stuff from types.py
38
+
39
+
27
40
  class _StringGlobs(dict):
28
41
  """
29
42
  Based on the fake globals dictionary used for annotations
@@ -99,6 +112,62 @@ def eval_hint(hint, context=None, *, recursion_limit=2):
99
112
  return hint
100
113
 
101
114
 
115
+ def call_annotate_func(annotate):
116
+ # Python 3.14 breaks the old methods of getting annotations
117
+ # The new annotationlib currently relies on 'ast' and 'functools'
118
+ # that this project tries to avoid importing.
119
+
120
+ # The basic logic is copied from there, however, replacing ForwardRef
121
+ # with a more basic class.
122
+ # While `annotationlib` is trying to return ForwardRef objects that can
123
+ # be evaluated later, this module only cares about annotations that can
124
+ # be evaluated at the point this function is called.
125
+ # As such we throw away the other information and just return strings
126
+ # instead of forwardrefs.
127
+
128
+ try:
129
+ raw_annotations = annotate(1)
130
+ except NameError:
131
+ pass
132
+ else:
133
+ return raw_annotations
134
+
135
+ # The annotate func may support forwardref natively
136
+ try:
137
+ raw_annotations = annotate(2)
138
+ except NotImplementedError:
139
+ pass
140
+ else:
141
+ return raw_annotations
142
+
143
+ # Not supported so we have to implement our own deferred handling
144
+ # Some modified logic from annotationlib
145
+ namespace = {**annotate.__builtins__, **annotate.__globals__}
146
+ globs = _StringGlobs(namespace)
147
+
148
+ # This handles closures where the variable is defined after get annotations is called.
149
+ if annotate.__closure__:
150
+ freevars = annotate.__code__.co_freevars
151
+ new_closure = []
152
+ for i, cell in enumerate(annotate.__closure__):
153
+ try:
154
+ cell.cell_contents
155
+ except ValueError:
156
+ if i < len(freevars):
157
+ name = freevars[i]
158
+ else:
159
+ name = "__cell__"
160
+ new_closure.append(_CellType(name))
161
+ else:
162
+ new_closure.append(cell)
163
+ closure = tuple(new_closure)
164
+ else:
165
+ closure = None
166
+
167
+ new_annotate = _FunctionType(annotate.__code__, globs, closure=closure)
168
+ return new_annotate(1)
169
+
170
+
102
171
  def get_ns_annotations(ns, eval_str=True):
103
172
  """
104
173
  Given a class namespace, attempt to retrieve the
@@ -112,36 +181,50 @@ def get_ns_annotations(ns, eval_str=True):
112
181
  :param eval_str: Attempt to evaluate string annotations (default to True)
113
182
  :return: dictionary of evaluated annotations
114
183
  """
115
- raw_annotations = ns.get("__annotations__", {})
116
184
 
117
- if not eval_str:
118
- return raw_annotations.copy()
185
+ # In 3.14 the 'canonical' method of getting annotations is to use __annotate__
186
+ # If this doesn't exist, check __annotations__ and treat as 3.13 or earlier.
187
+ annotate = ns.get("__annotate__")
119
188
 
120
- try:
121
- obj_modulename = ns["__module__"]
122
- except KeyError:
123
- obj_module = None
189
+ if annotate is not None:
190
+ raw_annotations = call_annotate_func(annotate)
124
191
  else:
125
- obj_module = sys.modules.get(obj_modulename, None)
192
+ raw_annotations = ns.get("__annotations__", {})
126
193
 
127
- if obj_module:
128
- obj_globals = vars(obj_module)
129
- else:
130
- obj_globals = {}
194
+ # Unlike annotationlib we still try to evaluate string annotations
195
+ # This will catch cases where someone has used a literal string for a
196
+ # single attribute.
197
+ if eval_str:
198
+ try:
199
+ obj_modulename = ns["__module__"]
200
+ except KeyError:
201
+ obj_module = None
202
+ else:
203
+ obj_module = sys.modules.get(obj_modulename, None)
204
+
205
+ if obj_module:
206
+ obj_globals = vars(obj_module)
207
+ else:
208
+ obj_globals = {}
131
209
 
132
- # Type parameters should be usable in hints without breaking
133
- # This is for Python 3.12+
134
- type_params = {
135
- repr(param): param
136
- for param in ns.get("__type_params__", ())
137
- }
210
+ # Type parameters should be usable in hints without breaking
211
+ # This is for Python 3.12+
212
+ type_params = {
213
+ repr(param): param
214
+ for param in ns.get("__type_params__", ())
215
+ }
138
216
 
139
- context = {**vars(builtins), **obj_globals, **type_params, **ns}
217
+ context = {**vars(builtins), **obj_globals, **type_params, **ns}
218
+
219
+ annotations = {
220
+ k: eval_hint(v, context)
221
+ for k, v in raw_annotations.items()
222
+ }
223
+
224
+ else:
225
+ annotations = raw_annotations.copy()
140
226
 
141
- return {
142
- k: eval_hint(v, context)
143
- for k, v in raw_annotations.items()
144
- }
227
+ return annotations
145
228
 
146
229
 
147
230
  def is_classvar(hint):
@@ -1,3 +1,4 @@
1
+ from collections.abc import Callable
1
2
  import typing
2
3
  import types
3
4
 
@@ -8,6 +9,11 @@ class _StringGlobs(dict):
8
9
  def __missing__(self, key: _T) -> _T: ...
9
10
 
10
11
 
12
+ def call_annotate_func(
13
+ annotate: Callable[[int], dict[str, type | typing.ForwardRef]]
14
+ ) -> dict[str, type | str]: ...
15
+
16
+
11
17
  def eval_hint(
12
18
  hint: type | str,
13
19
  context: None | dict[str, typing.Any] = None,
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: ducktools-classbuilder
3
- Version: 0.7.0
3
+ Version: 0.7.2
4
4
  Summary: Toolkit for creating class boilerplate generators
5
5
  Author: David C Ellis
6
6
  License: MIT License
@@ -32,6 +32,7 @@ Classifier: Programming Language :: Python :: 3.9
32
32
  Classifier: Programming Language :: Python :: 3.10
33
33
  Classifier: Programming Language :: Python :: 3.11
34
34
  Classifier: Programming Language :: Python :: 3.12
35
+ Classifier: Programming Language :: Python :: 3.13
35
36
  Classifier: Operating System :: OS Independent
36
37
  Classifier: License :: OSI Approved :: MIT License
37
38
  Requires-Python: >=3.8
@@ -0,0 +1,13 @@
1
+ ducktools/classbuilder/__init__.py,sha256=sHgrsySQDxcvnkL0GsQu9Q4Um2-9gRFyGeYGgNAEjag,32521
2
+ ducktools/classbuilder/__init__.pyi,sha256=t2KrEsEhKFbLpl0QeX0CiCy_VTRFRZO_2ABdfndRfZY,7939
3
+ ducktools/classbuilder/_version.py,sha256=iYP0OHZX_Sj2gXyYk7ivc79K_EYWflz05BN2AbALx90,52
4
+ ducktools/classbuilder/annotations.py,sha256=x-3936HcJzv04rga8k0fFTbu1656yDglVN6kCan4hiw,8203
5
+ ducktools/classbuilder/annotations.pyi,sha256=vW3YQIiKYYQJll9_B4oTkBwIh4nOy1AnU9Ny8_a0dRY,686
6
+ ducktools/classbuilder/prefab.py,sha256=6YOVVYYeuMF5gv9DnK-sCvNKxBaBoqDXNLUQ22-xINk,24097
7
+ ducktools/classbuilder/prefab.pyi,sha256=x2ioTpkhNjQXFeKABFOzE0xNeZ8f_W5vusmuAzE19mc,4491
8
+ ducktools/classbuilder/py.typed,sha256=la67KBlbjXN-_-DfGNcdOcjYumVpKG_Tkw-8n5dnGB4,8
9
+ ducktools_classbuilder-0.7.2.dist-info/LICENSE.md,sha256=6Thz9Dbw8R4fWInl6sGl8Rj3UnKnRbDwrc6jZerpugQ,1070
10
+ ducktools_classbuilder-0.7.2.dist-info/METADATA,sha256=o8V0NVephCbyJqbxiqqoIMerLLQsnQSYLQ5VrJWrUFk,10968
11
+ ducktools_classbuilder-0.7.2.dist-info/WHEEL,sha256=cVxcB9AmuTcXqmwrtPhNK88dr7IR_b6qagTj0UvIEbY,91
12
+ ducktools_classbuilder-0.7.2.dist-info/top_level.txt,sha256=uSDLtio3ZFqdwcsMJ2O5yhjB4Q3ytbBWbA8rJREganc,10
13
+ ducktools_classbuilder-0.7.2.dist-info/RECORD,,
@@ -1,5 +1,5 @@
1
1
  Wheel-Version: 1.0
2
- Generator: setuptools (70.3.0)
2
+ Generator: setuptools (74.1.2)
3
3
  Root-Is-Purelib: true
4
4
  Tag: py3-none-any
5
5
 
@@ -1,13 +0,0 @@
1
- ducktools/classbuilder/__init__.py,sha256=EylA7K40qGVctuGD_OLtcl-f0xqAICYw0MV-XqcDEhI,32869
2
- ducktools/classbuilder/__init__.pyi,sha256=NCLMWT3G0Z5lJky8EV_N6XcW8smScti6y2p163nZ8rM,7965
3
- ducktools/classbuilder/_version.py,sha256=TVtIAaEWunoxD4TTy8EMgVsVwLljxEqhLSu5_PMPjM8,52
4
- ducktools/classbuilder/annotations.py,sha256=17g1WnWfyMWBHKQp2HD_hvV-n7CKXy_zv8NTODpOsuU,5437
5
- ducktools/classbuilder/annotations.pyi,sha256=cTZQ-pp2IkfdvwHiU3pIySUzzBKxfOtO-e5PkA8TNwo,520
6
- ducktools/classbuilder/prefab.py,sha256=6YOVVYYeuMF5gv9DnK-sCvNKxBaBoqDXNLUQ22-xINk,24097
7
- ducktools/classbuilder/prefab.pyi,sha256=x2ioTpkhNjQXFeKABFOzE0xNeZ8f_W5vusmuAzE19mc,4491
8
- ducktools/classbuilder/py.typed,sha256=la67KBlbjXN-_-DfGNcdOcjYumVpKG_Tkw-8n5dnGB4,8
9
- ducktools_classbuilder-0.7.0.dist-info/LICENSE.md,sha256=6Thz9Dbw8R4fWInl6sGl8Rj3UnKnRbDwrc6jZerpugQ,1070
10
- ducktools_classbuilder-0.7.0.dist-info/METADATA,sha256=R5idmDAFadD3tnLKV1b1CtX937TGvjUWGUsQD6u9G6U,10917
11
- ducktools_classbuilder-0.7.0.dist-info/WHEEL,sha256=Z4pYXqR_rTB7OWNDYFOm1qRk0RX6GFP2o8LgvP453Hk,91
12
- ducktools_classbuilder-0.7.0.dist-info/top_level.txt,sha256=uSDLtio3ZFqdwcsMJ2O5yhjB4Q3ytbBWbA8rJREganc,10
13
- ducktools_classbuilder-0.7.0.dist-info/RECORD,,