worktoy 1.2.0.dev0__py3-none-any.whl → 1.2.0.dev1__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.
Files changed (33) hide show
  1. worktoy/__init__.py +1 -1
  2. worktoy/dispatch/_dispatcher.py +16 -9
  3. worktoy/keenum/__init__.py +6 -4
  4. worktoy/keenum/_kee_box.py +13 -2
  5. worktoy/keenum/_kee_flag.py +19 -12
  6. worktoy/keenum/_kee_flags.py +205 -134
  7. worktoy/keenum/_kee_flags_hook.py +11 -10
  8. worktoy/keenum/_kee_flags_meta.py +203 -115
  9. worktoy/keenum/_kee_flags_space.py +77 -109
  10. worktoy/keenum/_kee_member.py +44 -5
  11. worktoy/keenum/_kee_meta.py +52 -46
  12. worktoy/keenum/_kee_num.py +73 -5
  13. worktoy/keenum/_kee_space.py +37 -16
  14. worktoy/utilities/_class_body_template.py +16 -9
  15. worktoy/utilities/_resolve_mro.py +2 -2
  16. worktoy/utilities/_text_fmt.py +3 -2
  17. worktoy/utilities/_word_wrap.py +7 -4
  18. worktoy/waitaminute/__init__.py +19 -1
  19. worktoy/waitaminute/_alternative_warning.py +61 -0
  20. worktoy/waitaminute/_deprecated_promise.py +64 -0
  21. worktoy/waitaminute/_missing_variable.py +2 -1
  22. worktoy/waitaminute/_risk_warning.py +63 -0
  23. worktoy/waitaminute/_subclass_exception.py +2 -1
  24. worktoy/waitaminute/_work_toy_warning.py +164 -0
  25. worktoy/waitaminute/control_flow/__init__.py +18 -5
  26. worktoy/waitaminute/keenum/_kee_flag_duplicate.py +10 -9
  27. worktoy/waitaminute/keenum/_kee_type_exception.py +12 -7
  28. worktoy/work_test/_base_test.py +31 -1
  29. {worktoy-1.2.0.dev0.dist-info → worktoy-1.2.0.dev1.dist-info}/METADATA +2 -2
  30. {worktoy-1.2.0.dev0.dist-info → worktoy-1.2.0.dev1.dist-info}/RECORD +33 -29
  31. {worktoy-1.2.0.dev0.dist-info → worktoy-1.2.0.dev1.dist-info}/WHEEL +0 -0
  32. {worktoy-1.2.0.dev0.dist-info → worktoy-1.2.0.dev1.dist-info}/licenses/LICENSE +0 -0
  33. {worktoy-1.2.0.dev0.dist-info → worktoy-1.2.0.dev1.dist-info}/top_level.txt +0 -0
worktoy/__init__.py CHANGED
@@ -48,7 +48,7 @@ and the enclosing class is left without the decoration.
48
48
  # Copyright (c) 2025-2026 Asger Jon Vistisen
49
49
  from __future__ import annotations
50
50
 
51
- __version__ = '1.2.0-dev0'
51
+ __version__ = '1.2.0-dev1'
52
52
 
53
53
  from . import utilities
54
54
  from . import waitaminute
@@ -223,10 +223,13 @@ class Dispatcher(Object):
223
223
  signatures, most recent first.
224
224
  3. A cast of each argument that is not an instance, where a number
225
225
  class takes only a narrower number, 'int' to 'float' to 'complex',
226
- and every other class casts as 'typeCast' allows; farthest class
227
- first, so a subclass never redirects a call its parent handled
228
- through such a cast: the concrete signatures, the flexible
229
- declarations, then the variadic signatures.
226
+ and every other class casts as 'typeCast' allows: the concrete
227
+ signatures, then the flexible declarations, then the variadic
228
+ signatures, each kind farthest class first. A subclass therefore
229
+ never redirects a call its parent handled through a cast to a
230
+ signature of the same kind, but a concrete signature of a subclass
231
+ takes a call its parent handled through a cast to a flexible or a
232
+ variadic one.
230
233
  4. The same with every cast 'typeCast' allows, narrowing included, as
231
234
  '2.0' to the 'int' '2'.
232
235
  5. The fallback, if any, else 'DispatchException'.
@@ -444,7 +447,10 @@ class Dispatcher(Object):
444
447
  ) -> SigFuncList:
445
448
  """
446
449
  Adding a signature in a subclass must never redirect a call its parent
447
- already handled through a cast of the same tier.
450
+ already handled through a cast of the same tier to a signature of the
451
+ same kind. The cast pass tries the concrete signatures before the
452
+ flexible and the variadic ones, so this order holds within one kind
453
+ of signature only.
448
454
 
449
455
  Implementation
450
456
  --------------
@@ -715,10 +721,11 @@ class Dispatcher(Object):
715
721
  def matchCasts(args: tuple, cast: Callable) -> Any:
716
722
  """The function, and the arguments in the order it takes them, of
717
723
  the registration accepting 'args' when 'cast' is applied to each
718
- argument that is not an instance, farthest class first; within a
719
- class the concrete signatures in registration order, then the
720
- flexible declarations, then the variadic ones, the most recent
721
- first. None when none accepts the call."""
724
+ argument that is not an instance: the concrete signatures, then the
725
+ flexible declarations, then the variadic ones, each kind farthest
726
+ class first, and within a class the concrete and flexible ones in
727
+ registration order, the variadic ones most recent first. None when
728
+ none accepts the call."""
722
729
  for sig, func in castFuncs:
723
730
  if len(args) != len(sig):
724
731
  continue
@@ -3,10 +3,12 @@ The 'worktoy.keenum' package builds two enumeration systems on the
3
3
  metaclass and descriptor machinery from 'worktoy.mcls' and
4
4
  'worktoy.desc'. 'KeeNum' is the value enumeration: 'Kee' members declared
5
5
  in the class body are collected by a space hook and frozen into typed
6
- members by 'KeeMeta'. 'KeeFlags' is the bitmask-flag enumeration: each
7
- 'KeeFlag' is one bit, and 'KeeFlagsMeta' materializes every combination as
8
- a member. 'KeeBox' adapts either system for use as an 'AttriBox' field
9
- type.
6
+ members by 'KeeMeta'. 'KeeFlags' is the bitmask-flag enumeration: its
7
+ flags are declared with 'Kee' as well, each one bit, and 'KeeFlagsMeta'
8
+ gives the class every combination of them as a member. In both systems
9
+ an enumeration may be based on several, and holds the very members of
10
+ its bases. 'KeeBox', deprecated, adapts either system for use as an
11
+ 'AttriBox' field type.
10
12
 
11
13
  KeeNum machinery:
12
14
 
@@ -10,7 +10,8 @@ from typing import TYPE_CHECKING
10
10
 
11
11
  from . import KeeMeta, KeeFlagsMeta
12
12
  from ..desc import AttriBox
13
- from ..waitaminute import TypeException
13
+ from ..utilities import textFmt
14
+ from ..waitaminute import TypeException, DeprecatedPromise
14
15
  from ..waitaminute.keenum import KeeBoxException, \
15
16
  KeeBoxValueError, KeeBoxTypeError
16
17
 
@@ -20,6 +21,12 @@ if TYPE_CHECKING: # pragma: no cover, no mutate
20
21
 
21
22
  class KeeBox(AttriBox):
22
23
  """
24
+ 'KeeBox' is deprecated: it is no longer a promised feature beginning
25
+ with the next major update, and every subscript of it gives a
26
+ 'DeprecatedPromise' at the line that wrote the subscript. It works
27
+ as it did. An 'AttriBox' over the enumeration, with the member itself
28
+ as the default, declares the same field.
29
+
23
30
  A field typed with an enumeration is declared with the member it
24
31
  starts as, and a project wants to write that member the way it
25
32
  thinks of it: by name, by the arguments of the value it carries, by
@@ -171,8 +178,12 @@ class KeeBox(AttriBox):
171
178
  'TypeException' otherwise, before delegating to
172
179
  'AttriBox.__class_getitem__'. The restriction simplifies the
173
180
  implementation; plain 'AttriBox' performs no such check and accepts
174
- every 'type'.
181
+ every 'type'. Every subscript first gives the deprecation notice of
182
+ 'KeeBox', at the line that wrote the subscript.
175
183
  """
184
+ info = """Declare the field with 'AttriBox' instead, giving the
185
+ member itself as the default."""
186
+ DeprecatedPromise(KeeBox, textFmt(info)).warn()
176
187
  if isinstance(fieldType, KeeMeta) or isinstance(fieldType, KeeFlagsMeta):
177
188
  return super().__class_getitem__(fieldType)
178
189
  raise TypeException('fieldType', fieldType, KeeMeta, KeeFlagsMeta)
@@ -9,7 +9,7 @@ import typing
9
9
  from typing import TYPE_CHECKING
10
10
 
11
11
  from ..utilities import textFmt, maybe
12
- from ..waitaminute import MissingVariable, TypeException
12
+ from ..waitaminute import MissingVariable, TypeException, DeprecatedPromise
13
13
 
14
14
  if TYPE_CHECKING: # pragma: no cover, no mutate
15
15
  from typing import Any, Tuple, Self, Iterator, Never
@@ -19,13 +19,16 @@ if TYPE_CHECKING: # pragma: no cover, no mutate
19
19
  class KeeFlag:
20
20
  """
21
21
  KeeFlag declares one single-bit flag inside a 'KeeFlags' class body.
22
+ It is deprecated: each 'KeeFlag' made gives a 'DeprecatedPromise' at
23
+ the line that made it, and declares its flag as it did. A 'Kee'
24
+ declares a flag instead, as 'READ = Kee[str]()'.
25
+
22
26
  Despite the name it is not itself an enumeration; the 'KeeFlags'
23
27
  metaclass reads the declared flags and builds the members, one per
24
- combination of flags (including the all-low 'NULL' member).
25
-
26
- Please note that the actual instances of this class are *not* the
27
- members of the enumeration. 'KeeFlags' manages a container of these.
28
- Then the members are created as wrappers on these instances.
28
+ combination of flags, the flag itself among them. The 'KeeFlag' is the
29
+ declaration of a flag, kept on the member as its 'kee', and receives
30
+ the class that built the flag as its owner and the bit of the flag as
31
+ its index.
29
32
 
30
33
  Where the 'Kee' class allows the novel syntactic sugar of 'Kee[int](1)',
31
34
  'KeeFlag' requires the owning 'KeeFlags' class to specify the type of the
@@ -178,6 +181,9 @@ class KeeFlag:
178
181
  # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
179
182
 
180
183
  def __init__(self, *args, **kwargs) -> None:
184
+ info = """Declare the flag with 'Kee' instead, as 'READ =
185
+ Kee[str]()'."""
186
+ DeprecatedPromise(KeeFlag, textFmt(info)).warn()
181
187
  self.__pos_args__ = args
182
188
  self.__key_args__ = kwargs
183
189
 
@@ -187,8 +193,9 @@ class KeeFlag:
187
193
  carrying over its constructor arguments, name, and index (the index
188
194
  overridable via the argument).
189
195
  """
190
- cls = type(self)
191
- cloned = cls(*self.args, **self.kwargs)
196
+ cloned = object.__new__(type(self))
197
+ cloned.__pos_args__ = self.__pos_args__
198
+ cloned.__key_args__ = self.__key_args__
192
199
  cloned.__field_owner__ = owner
193
200
  cloned.__field_name__ = self.__field_name__
194
201
  cloned.__member_index__ = maybe(index, self.__member_index__)
@@ -200,14 +207,14 @@ class KeeFlag:
200
207
  # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
201
208
 
202
209
  if TYPE_CHECKING: # pragma: no cover, no mutate
203
- @typing.overload
210
+ @typing.overload # pragma: no mutate
204
211
  def __or__(self, other: Self) -> Self: ...
205
212
 
206
- @typing.overload
213
+ @typing.overload # pragma: no mutate
207
214
  def __and__(self, other: Self) -> Self: ...
208
215
 
209
- @typing.overload
216
+ @typing.overload # pragma: no mutate
210
217
  def __xor__(self, other: Self) -> Self: ...
211
218
 
212
- @typing.overload
219
+ @typing.overload # pragma: no mutate
213
220
  def __invert__(self) -> Self: ...
@@ -8,88 +8,112 @@ from __future__ import annotations
8
8
  from typing import TYPE_CHECKING
9
9
 
10
10
  from ..utilities import textFmt
11
+ from ..waitaminute import DeprecatedPromise
11
12
  from ..waitaminute.keenum import KeeWriteOnceError, KeeResolveError
12
- from . import KeeFlag, KeeFlagsMeta
13
+ from . import Kee, KeeFlagsMeta
13
14
 
14
15
  if TYPE_CHECKING: # pragma: no cover, no mutate
15
- from typing import Any, Iterator, Never, Optional, Self
16
+ from typing import Any, Callable, Iterator, Never, Optional, Self
17
+
18
+ # The description of the deprecation of the bit mask of a member.
19
+ _MASK = """The bit mask belongs to the class, not to the member: 'Flags[x]'
20
+ gives the member of mask 'x', and iterating 'Flags' gives its members in
21
+ the order of their masks."""
16
22
 
17
23
 
18
24
  class KeeFlags(metaclass=KeeFlagsMeta, _root=True):
19
25
  """
20
- Base class for bitmask-flag enumerations. Each KeeFlags subclass
21
- declares 'KeeFlag()' fields in its body, one per single-bit flag;
22
- the metaclass then materializes every combination of those flags as
23
- a concrete member at class-creation time.
26
+ Base class for bitmask-flag enumerations. A subclass declares its
27
+ flags in its body with 'Kee', as 'READ = Kee[str]()', and the
28
+ metaclass gives the class one member per combination of its flags.
29
+
30
+ class UserPermission(KeeFlags):
31
+ READ = Kee[str]()
32
+ EXEC = Kee[str]()
33
+
34
+ class AdminPermission(KeeFlags):
35
+ WRITE = Kee[str]()
36
+ DEL = Kee[str]()
37
+
38
+ class Permission(UserPermission, AdminPermission):
39
+ pass
40
+
41
+ Every member is a combination of flags. A flag is the combination of
42
+ itself, and 'NULL', which this root builds, is the one member that
43
+ combines none, inherited by every flags class.
24
44
 
25
45
  Cost (read before declaring a large enum)
26
46
  -----------------------------------------
27
47
 
28
- A KeeFlags class with N single-bit flags materializes 2 ** N
29
- members eagerly during class definition, each with its name, the
30
- names of its flags and its hash worked out once. Measured on one
31
- desktop machine under Python 3.15, the class statement took:
48
+ A flags class with N flags holds 2 ** N members and builds those no
49
+ other class built for the same flags, each with its name, the names of
50
+ its flags and its hash worked out once. Measured on one desktop
51
+ machine under Python 3.15, the class statement of a class of fresh
52
+ flags took:
32
53
 
33
54
  N = 8 -> 256 members about a millisecond
34
55
  N = 12 -> 4096 members about 15 milliseconds
35
56
  N = 16 -> 65,536 members about 0.3 seconds, and 72 MB
36
57
 
37
58
  The cost is paid once, at import, and grows four times for every two
38
- flags added. Every lookup is one step whatever N is: by index, by
39
- name in any case and order, by value when every value hashes, and
40
- through the operators.
59
+ flags added. Every lookup is one step whatever N is: by mask, by name
60
+ in any case and order, by value when every value hashes, and through
61
+ the operators.
62
+
63
+ Members shared along the lineage
64
+ --------------------------------
65
+
66
+ A flags class holds the flags of its bases first, in the order of the
67
+ bases, and its own after them. One member stands for each set of flags
68
+ in the whole process, so a class holds the very members of its bases,
69
+ 'Extended.READ is Permission.READ', and a combination of flags of two
70
+ bases is built by the first class combining them and bound by every
71
+ later one. A member belongs to the class that built it: its 'flags'
72
+ are those of that class, its 'lows' the flags of that class that are
73
+ low in it, and its value comes from the '_getValue' of that class.
41
74
 
42
75
  Member attributes
43
76
  -----------------
44
77
 
45
- - 'flags': all single-bit flags declared on the class (mirrors the
46
- class-level 'flags'; not member-specific).
47
- - 'highs': the flags that are HIGH for the member.
48
- - 'lows': the flags that are LOW for the member.
49
- - 'names': a frozenset of the names of the HIGH flags.
50
- - 'index' / 'value': the member's bitmask integer (value defaults
51
- to the index). A subclass reimplements '_getValue' to give its
52
- members other values; it is read once per member, as the class is
53
- created.
54
- - 'name': the canonical name, the HIGH flag names joined by '_', or
55
- 'NULL' when no flag is HIGH.
56
-
57
- Naming and lookup
58
- -----------------
59
-
60
- A combined member's canonical name joins its HIGH flag names in
61
- declaration order ('FileAccess.READ_EXECUTE', never
62
- 'FileAccess.EXECUTE_READ'), and attribute access resolves only that
63
- canonical name. Subscripting and calling are order- and
64
- case-insensitive: 'cls["EXECUTE_READ"]', 'cls["execute_read"]', and
65
- 'cls["READ", "EXECUTE"]' all resolve to the same member, a repeated name
66
- collapses, and an unknown name raises 'KeeResolveError', as an unknown
67
- index or value does and as a 'KeeNum' miss does. Since '_' joins the
68
- flag names in a canonical name, a flag name may not contain '_' itself;
69
- declaring one raises 'KeeFlagNameError' in the class body.
70
-
71
- Members across a lineage
72
- ------------------------
73
-
74
- A flags class based on another holds the flags of its base first and
75
- members of its own, so no member object is shared between the two.
76
- Across the lineage a member is identified by the names of its high
77
- flags: a member of the base or of the subclass is equal to the member
78
- here with the same flags and hashes alike, resolves through a call, a
79
- subscript or 'typeCast' to this class's own member when this class
80
- holds every one of its flags, and is refused with 'KeeResolveError'
81
- otherwise, is in the class exactly when such a member exists, and
82
- takes part in the operators, where the class of the left operand
83
- answers when it holds every flag and the class of the right one
84
- answers through the reflected operator otherwise. Members of
85
- unrelated flags classes are strangers to each other.
78
+ - 'name': the flag names joined by '_' in the order of the class that
79
+ built it, or 'NULL'. A class binds each member at the name joining
80
+ its flags in its own order.
81
+ - 'names': a frozenset of the names of the high flags.
82
+ - 'highs': the flags that are high in the member, the flag members
83
+ themselves; iterating a member gives them.
84
+ - 'lows': the flags of the class that built the member that are low.
85
+ - 'flags': the flags of the class that built the member.
86
+ - 'value': the value of a flag declared with a 'Kee' is that of the
87
+ 'Kee', so 'Kee[str]()' gives the name; every other member is valued
88
+ by its name. A subclass reimplements '_getValue' to give the members
89
+ it builds other values; it is read once per member, after the class
90
+ has its flags. 'valueType' is the type of the value of the first
91
+ flag of the class, and no combination may contain a member whose
92
+ value is not an instance of it: every flag of a class shares the
93
+ type, while the value of a combination is free, and 'NULL' is
94
+ exempt, since it contains no member.
95
+ - 'kee': the declaration of a flag, or None for any other member.
96
+ - 'owners': the flags classes holding the member, in order of
97
+ creation.
98
+ - 'index': deprecated, the bit mask of the member in the class that
99
+ built it.
100
+
101
+ Equality is identity, and a member hashes by the names of its flags.
102
+ '|', '&' and '^' give the member of the resulting set of flags, and
103
+ refuse with 'TypeError' when no class holds that set. '~member' is the
104
+ member whose flags are the lows of 'member'; '~NULL' raises
105
+ 'ZeroDivisionError', since there is no universal combination to invert
106
+ to. 'NULL' is falsy and every other member truthy.
86
107
 
87
108
  Like 'KeeNum' members, the members are write-once constants: any
88
109
  attempt to set or delete an attribute on a member raises
89
110
  'KeeWriteOnceError', as does rebinding or deleting the member name on
90
111
  the owning class. The constructor writes past that with
91
- 'object.__setattr__'. A member needing extra attributes should come
92
- from a subclass declaring them.
112
+ 'object.__setattr__'. A copy of a member is the member, and a member
113
+ pickles as a lookup of its name on the class that built it. The text
114
+ of a member is no promise: it currently names its one owner,
115
+ '<Permission>.READ', or the root once several classes hold it,
116
+ '<KeeFlags>.READ'.
93
117
  """
94
118
 
95
119
  # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
@@ -99,52 +123,68 @@ class KeeFlags(metaclass=KeeFlagsMeta, _root=True):
99
123
  # Class Variables (type hints)
100
124
  __member_list__: list[Self]
101
125
  __member_dict__: dict[frozenset[str], Self]
126
+ __flag_order__: tuple[Self, ...]
102
127
 
103
128
  # Private Variables
104
129
  __field_owner__ = None
105
130
  __field_name__ = None
106
131
  __member_hash__: Optional[int] = None
132
+ __member_flags__: tuple = ()
133
+ __member_index__: Optional[int] = None
134
+ __member_owners__: Optional[list] = None
107
135
 
108
136
  # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
109
137
  # GETTERS # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
110
138
  # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
111
139
 
112
- def _getFlagsFromType(self, ) -> Any:
140
+ def _getFlagsFromType(self, ) -> list[Self]:
113
141
  """
114
- The 'KeeFlagsMeta' metaclass provides the helpful 'flags' descriptor
115
- allowing inspection of all the flags available. The descriptor is then
116
- available on the subclasses of 'KeeFlags', but *not* on the
117
- instances themselves. Therefore, the 'KeeFlags' class mirrors it.
142
+ The 'flags' of a member are those of the class that built it, which
143
+ the metaclass gives the class as 'flags'.
118
144
  """
119
145
  return type(self).flags
120
146
 
121
147
  def _getValue(self) -> Any:
122
148
  """
123
149
  The value of a member is what a project reads off it, and what the
124
- class resolves a member from. The base gives every member its index
125
- as its value; a subclass reimplements this method to give any object
126
- from any member, as 'FileAccess' in the tests gives bytes. It is read
127
- once per member, as the class is created. Values of one immutable
128
- type are recommended, not required, and several members may share
129
- one value, in which case the lowest-indexed member answers for it.
150
+ class resolves a member from. A flag declared with a 'Kee' is valued
151
+ as the 'Kee' is, so 'Kee[str]()' gives the name, and every other
152
+ member is valued by its name. A subclass reimplements this method to
153
+ give the members it builds any other object; it is read once per
154
+ member, after the class has its flags. Several members may share one
155
+ value, in which case the lowest-indexed member answers for it.
130
156
  """
131
- return self.index
157
+ if isinstance(self.kee, Kee):
158
+ return self.kee.getValue()
159
+ return self.name
132
160
 
133
- def _getLows(self) -> Iterator[KeeFlag]:
134
- index = self.index
135
- for flag in type(self).__flag_clones__:
136
- if not index & (1 << flag.index):
137
- yield flag
161
+ def _getHighs(self) -> Iterator[Self]:
162
+ yield from self.__member_flags__
138
163
 
139
- def _getHighs(self) -> Iterator[KeeFlag]:
140
- index = self.index
141
- for flag in type(self).__flag_clones__:
142
- if index & (1 << flag.index):
164
+ def _getLows(self) -> Iterator[Self]:
165
+ highs = self.__member_flags__
166
+ for flag in type(self).__flag_order__:
167
+ if not any(flag is high for high in highs):
143
168
  yield flag
144
169
 
170
+ def _readIndex(self) -> int:
171
+ """
172
+ The 'index' of a member is deprecated: the bit mask belongs to the
173
+ class, which answers 'Flags[x]', not to the member. A read still
174
+ gives the mask in the class that built the member, with a
175
+ 'DeprecatedPromise' at the line that read it.
176
+ """
177
+ DeprecatedPromise('worktoy.keenum.KeeFlags.index', textFmt(_MASK)).warn()
178
+ return self.__member_index__
179
+
180
+ def _getOwners(self) -> tuple[type, ...]:
181
+ return (*self.__member_owners__,)
182
+
145
183
  flags = property(_getFlagsFromType)
146
184
  lows = property(_getLows)
147
185
  highs = property(_getHighs)
186
+ index = property(_readIndex)
187
+ owners = property(_getOwners)
148
188
 
149
189
  # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
150
190
  # Python API # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
@@ -155,7 +195,7 @@ class KeeFlags(metaclass=KeeFlagsMeta, _root=True):
155
195
  """
156
196
  The '__cast_as__' hook lets 'typeCast' resolve a value to the member
157
197
  it identifies, as calling the class does: a member passes, a name in
158
- any case and order, a tuple of names, an index or a value resolves,
198
+ any case and order, a tuple of names, a mask or a value resolves,
159
199
  and one the class cannot resolve is declined with 'NotImplemented',
160
200
  so 'typeCast' raises its own refusal and an 'AttriBox' over the
161
201
  class, or an overload naming it, refuses it as any value it cannot
@@ -197,73 +237,56 @@ class KeeFlags(metaclass=KeeFlagsMeta, _root=True):
197
237
 
198
238
  def __reduce__(self) -> tuple:
199
239
  """
200
- A member pickles as a lookup of its canonical name on its class, so
201
- it unpickles as the member itself.
240
+ A member pickles as a lookup of its name on the class that built it,
241
+ so it unpickles as the member itself.
202
242
  """
203
243
  return getattr, (type(self), self.name)
204
244
 
205
245
  def __bool__(self) -> bool:
206
- """The NULL member (no flags HIGH) is falsy. Any member with at
207
- least one flag HIGH is truthy, mirroring the truthiness of the
208
- underlying bitmask."""
209
- return True if self.index else False
246
+ """'NULL', which combines no flags, is falsy. Every other member is
247
+ truthy, mirroring the truthiness of the underlying bitmask."""
248
+ return True if self.__member_flags__ else False
210
249
 
211
- def __iter__(self) -> Iterator[KeeFlag]:
250
+ def __iter__(self) -> Iterator[Self]:
212
251
  yield from self.highs
213
252
 
214
253
  def __str__(self, ) -> str:
215
- infoSpec = """%s.%s [%d]"""
216
- clsName = type(self).__name__
217
- info = infoSpec % (clsName, self.name, self.index)
218
- return textFmt(info)
254
+ """
255
+ The text names the one class holding the member, or the root once
256
+ several do. It is no promise.
257
+ """
258
+ owners = self.__member_owners__
259
+ if len(owners) == 1:
260
+ return '<%s>.%s' % (owners[0].__name__, self.name)
261
+ root = type(type(self)).__kee_class__
262
+ return '<%s>.%s' % (root.__name__, self.name)
219
263
 
220
264
  __repr__ = __str__
221
265
 
222
- def __eq__(self, other: Any) -> bool:
223
- cls, otherCls = type(self), type(other)
224
- if otherCls is cls:
225
- return True if self is other else False
226
- if not isinstance(otherCls, KeeFlagsMeta):
227
- return NotImplemented
228
- if issubclass(otherCls, cls) or issubclass(cls, otherCls):
229
- return True if self.names == other.names else False
230
- return NotImplemented
231
-
232
266
  def __hash__(self, ) -> int:
233
267
  return self.__member_hash__
234
268
 
235
- def _asOwn(self, other: Any) -> Any:
269
+ def _combine(self, other: Any, merge: Callable) -> Any:
236
270
  """
237
- An operator takes a member of this class or of a related one, and
238
- works on the member of this class with the other's flags; anything
239
- else, a member of an unrelated class or a member with a flag this
240
- class lacks, gives 'None', so the operator answers 'NotImplemented'
241
- and Python asks the other operand.
271
+ The operators work on the flags of the two members alone, so neither
272
+ class has a say: the result is the member of the resulting set of
273
+ flags, whichever class built it, or 'NotImplemented' when 'other' is
274
+ no flags member or no class holds that set.
242
275
  """
243
- cls = type(self)
244
- if type(other) is cls:
245
- return other
246
276
  if not isinstance(type(other), KeeFlagsMeta):
247
- return None
248
- return cls._fromMember(other)
277
+ return NotImplemented
278
+ mine = frozenset(self.__member_flags__)
279
+ theirs = frozenset(other.__member_flags__)
280
+ return KeeFlagsMeta._findCombination(merge(mine, theirs))
249
281
 
250
282
  def __or__(self, other: Any) -> Any:
251
- own = self._asOwn(other)
252
- if own is None:
253
- return NotImplemented
254
- return type(self).__member_list__[self.index | own.index]
283
+ return self._combine(other, frozenset.union)
255
284
 
256
285
  def __and__(self, other: Any) -> Any:
257
- own = self._asOwn(other)
258
- if own is None:
259
- return NotImplemented
260
- return type(self).__member_list__[self.index & own.index]
286
+ return self._combine(other, frozenset.intersection)
261
287
 
262
288
  def __xor__(self, other: Any) -> Any:
263
- own = self._asOwn(other)
264
- if own is None:
265
- return NotImplemented
266
- return type(self).__member_list__[self.index ^ own.index]
289
+ return self._combine(other, frozenset.symmetric_difference)
267
290
 
268
291
  # The three operators commute, so the reflected forms are the same.
269
292
  __ror__ = __or__
@@ -271,27 +294,75 @@ class KeeFlags(metaclass=KeeFlagsMeta, _root=True):
271
294
  __rxor__ = __xor__
272
295
 
273
296
  def __invert__(self, ) -> Self:
274
- members = type(self).__member_list__
275
- return members[(len(members) - 1) ^ self.index]
297
+ """
298
+ The inverse of a member is the member whose flags are its lows, the
299
+ flags of the class that built it that are low in it. 'NULL' combines
300
+ no flags and belongs to no class with flags, so it has no inverse.
301
+ """
302
+ if not self.__member_flags__:
303
+ info = """'NULL' combines no flags, and there is no universal
304
+ combination for it to invert to."""
305
+ raise ZeroDivisionError(textFmt(info))
306
+ return KeeFlagsMeta._findCombination(frozenset(self.lows))
307
+
308
+ def __int__(self) -> int:
309
+ """
310
+ 'int(member)' gives the deprecated bit mask, with a
311
+ 'DeprecatedPromise'; see '_readIndex'.
312
+ """
313
+ info = textFmt(_MASK)
314
+ DeprecatedPromise('worktoy.keenum.KeeFlags.__int__', info).warn()
315
+ return self.__member_index__
316
+
317
+ def __index__(self) -> int:
318
+ """
319
+ A member used as an index gives the deprecated bit mask, with a
320
+ 'DeprecatedPromise'; see '_readIndex'.
321
+ """
322
+ info = textFmt(_MASK)
323
+ DeprecatedPromise('worktoy.keenum.KeeFlags.__index__', info).warn()
324
+ return self.__member_index__
276
325
 
277
326
  # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
278
327
  # CONSTRUCTORS # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
279
328
  # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
280
329
 
281
- def __init__(self, index: int) -> None:
330
+ def __init__(self, highs: tuple, mask: int, kee: Any = None) -> None:
282
331
  """
283
- The member of the bit mask 'index' stores its index, the names of its
284
- high flags, its canonical name, its hash and its value as plain
285
- attributes, with its class and name as '__field_owner__' and
286
- '__field_name__'.
332
+ A member stores its high flags, its bit mask in the class building
333
+ it, its canonical name, the names of its flags, its hash and its
334
+ declaration as plain attributes. A flag, given its declaration, is
335
+ the combination of itself and takes the name of the declaration. The
336
+ value is settled by the metaclass through '_settleValue' once the
337
+ class has its flags.
287
338
  """
288
- object.__setattr__(self, 'index', index)
289
- highNames = [flag.name for flag in self.highs]
290
- names = frozenset(highNames)
291
- name = '_'.join(highNames) or 'NULL'
292
- object.__setattr__(self, 'names', names)
339
+ if kee is None:
340
+ name = str.join('_', [flag.name for flag in highs]) or 'NULL'
341
+ else:
342
+ name = kee.name
343
+ highs = (self,)
293
344
  object.__setattr__(self, 'name', name)
345
+ object.__setattr__(self, 'kee', kee)
346
+ object.__setattr__(self, '__member_flags__', highs)
347
+ object.__setattr__(self, '__member_index__', mask)
348
+ object.__setattr__(self, '__member_owners__', [])
349
+ names = frozenset(flag.name for flag in highs)
350
+ object.__setattr__(self, 'names', names)
294
351
  object.__setattr__(self, '__member_hash__', hash(names))
295
352
  object.__setattr__(self, '__field_owner__', type(self))
296
353
  object.__setattr__(self, '__field_name__', name)
354
+
355
+ def _settleValue(self) -> None:
356
+ """
357
+ The metaclass reads the value once, after the class building the
358
+ member has all its flags, since a '_getValue' may read the lows.
359
+ """
297
360
  object.__setattr__(self, 'value', self._getValue())
361
+
362
+ def _addOwner(self, cls: type) -> None:
363
+ """
364
+ The metaclass records each flags class holding the member as it binds
365
+ it. The list is changed in place, which the frozen member allows,
366
+ since nothing is assigned.
367
+ """
368
+ self.__member_owners__.append(cls)