literalenum 0.2.0__py3-none-any.whl → 0.4.0__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.
- literalenum/stubgen.py +58 -18
- {literalenum-0.2.0.dist-info → literalenum-0.4.0.dist-info}/METADATA +1 -3
- {literalenum-0.2.0.dist-info → literalenum-0.4.0.dist-info}/RECORD +7 -7
- typing_literalenum.py +98 -0
- {literalenum-0.2.0.dist-info → literalenum-0.4.0.dist-info}/WHEEL +0 -0
- {literalenum-0.2.0.dist-info → literalenum-0.4.0.dist-info}/entry_points.txt +0 -0
- {literalenum-0.2.0.dist-info → literalenum-0.4.0.dist-info}/licenses/LICENSE +0 -0
literalenum/stubgen.py
CHANGED
|
@@ -129,10 +129,10 @@ def _render_enum_blocks(enums: list[EnumInfo]) -> str:
|
|
|
129
129
|
|
|
130
130
|
out: list[str] = []
|
|
131
131
|
for e in sorted(enums, key=lambda x: x.name):
|
|
132
|
-
|
|
132
|
+
T = f"{e.name}T"
|
|
133
133
|
values = list(e.members.values())
|
|
134
134
|
literal_union = ", ".join(_py_literal(v) for v in values) if values else ""
|
|
135
|
-
out.append(f"{
|
|
135
|
+
out.append(f"{T}: TypeAlias = Literal[{literal_union}]\n\n")
|
|
136
136
|
|
|
137
137
|
base = _enum_base_decl(e)
|
|
138
138
|
inherited = _inherited_member_names(e)
|
|
@@ -141,27 +141,62 @@ def _render_enum_blocks(enums: list[EnumInfo]) -> str:
|
|
|
141
141
|
own_members = [(k, v) for (k, v) in e.members.items() if k not in inherited]
|
|
142
142
|
|
|
143
143
|
out.append(f"class {e.name}({base}):\n")
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
else:
|
|
144
|
+
|
|
145
|
+
# -- Members --
|
|
146
|
+
if own_members:
|
|
148
147
|
for k, v in own_members:
|
|
149
148
|
out.append(f" {k}: Final[Literal[{_py_literal(v)}]] = {_py_literal(v)}\n")
|
|
149
|
+
else:
|
|
150
|
+
out.append(" ...\n")
|
|
151
|
+
out.append("\n")
|
|
152
|
+
|
|
153
|
+
# -- Mappings --
|
|
154
|
+
out.append(f" mapping: ClassVar[MappingProxyType[str, {T}]]\n")
|
|
155
|
+
out.append(f" unique_mapping: ClassVar[MappingProxyType[str, {T}]]\n")
|
|
156
|
+
out.append(f" __members__: ClassVar[MappingProxyType[str, {T}]]\n\n")
|
|
157
|
+
|
|
158
|
+
# -- Dict-like --
|
|
159
|
+
out.append(" @classmethod\n")
|
|
160
|
+
out.append(" def keys(cls) -> tuple[str, ...]: ...\n")
|
|
161
|
+
out.append(" @classmethod\n")
|
|
162
|
+
out.append(f" def values(cls) -> tuple[{T}, ...]: ...\n")
|
|
163
|
+
out.append(" @classmethod\n")
|
|
164
|
+
out.append(f" def items(cls) -> tuple[tuple[str, {T}], ...]: ...\n\n")
|
|
150
165
|
|
|
151
|
-
|
|
152
|
-
out.append(
|
|
166
|
+
# -- Alias introspection --
|
|
167
|
+
out.append(" @classmethod\n")
|
|
168
|
+
out.append(f" def names(cls, value: {T}) -> tuple[str, ...]: ...\n")
|
|
169
|
+
out.append(" @classmethod\n")
|
|
170
|
+
out.append(f" def canonical_name(cls, value: {T}) -> str: ...\n\n")
|
|
153
171
|
|
|
172
|
+
# -- Validation --
|
|
173
|
+
out.append(" @classmethod\n")
|
|
174
|
+
out.append(f" def is_valid(cls, x: object) -> TypeGuard[{T}]: ...\n")
|
|
175
|
+
out.append(" @classmethod\n")
|
|
176
|
+
out.append(f" def validate(cls, x: object) -> {T}: ...\n\n")
|
|
177
|
+
|
|
178
|
+
# -- Container protocol --
|
|
179
|
+
out.append(f" def __iter__(cls) -> Iterator[{T}]: ...\n")
|
|
180
|
+
out.append(f" def __reversed__(cls) -> Iterator[{T}]: ...\n")
|
|
181
|
+
out.append(" def __len__(cls) -> int: ...\n")
|
|
182
|
+
out.append(" def __bool__(cls) -> bool: ...\n")
|
|
183
|
+
out.append(" def __contains__(cls, value: object) -> bool: ...\n")
|
|
184
|
+
out.append(f" def __getitem__(cls, key: str) -> {T}: ...\n")
|
|
185
|
+
out.append(" def __repr__(cls) -> str: ...\n\n")
|
|
186
|
+
|
|
187
|
+
# -- Operators --
|
|
188
|
+
out.append(" def __or__(cls, other: LiteralEnumMeta) -> LiteralEnumMeta: ...\n")
|
|
189
|
+
out.append(" def __and__(cls, other: LiteralEnumMeta) -> LiteralEnumMeta: ...\n\n")
|
|
190
|
+
|
|
191
|
+
# -- Constructor --
|
|
154
192
|
if e.call_to_validate:
|
|
155
193
|
out.append(" @overload\n")
|
|
156
|
-
out.append(f" def __new__(cls, value: {
|
|
194
|
+
out.append(f" def __new__(cls, value: {T}) -> {T}: ...\n")
|
|
157
195
|
out.append(" @overload\n")
|
|
158
|
-
out.append(f" def __new__(cls, value: object) -> {
|
|
196
|
+
out.append(f" def __new__(cls, value: object) -> {T}: ...\n\n")
|
|
159
197
|
else:
|
|
160
198
|
out.append(f" def __new__(cls, value: Never) -> NoReturn: ...\n\n")
|
|
161
199
|
|
|
162
|
-
out.append(" @classmethod\n")
|
|
163
|
-
out.append(f" def is_member(cls, value: object) -> TypeGuard[{alias}]: ...\n\n")
|
|
164
|
-
|
|
165
200
|
return "".join(out)
|
|
166
201
|
|
|
167
202
|
|
|
@@ -202,8 +237,9 @@ def _render_overlay_stub_module(enums: list[EnumInfo]) -> str:
|
|
|
202
237
|
"""
|
|
203
238
|
out: list[str] = []
|
|
204
239
|
out.append("from __future__ import annotations\n")
|
|
205
|
-
out.append("from
|
|
206
|
-
out.append("from
|
|
240
|
+
out.append("from types import MappingProxyType\n")
|
|
241
|
+
out.append("from typing import ClassVar, Final, Iterator, Literal, Never, NoReturn, TypeAlias, TypeGuard, overload\n")
|
|
242
|
+
out.append("from literalenum import LiteralEnum, LiteralEnumMeta\n\n")
|
|
207
243
|
out.append(_render_enum_blocks(enums))
|
|
208
244
|
return "".join(out)
|
|
209
245
|
|
|
@@ -212,8 +248,9 @@ def _render_overlay_stub_module(enums: list[EnumInfo]) -> str:
|
|
|
212
248
|
# Adjacent stubs (preserve module)
|
|
213
249
|
# ----------------------------
|
|
214
250
|
|
|
215
|
-
|
|
216
|
-
|
|
251
|
+
_TYPES_INJECT = "from types import MappingProxyType"
|
|
252
|
+
_TYPING_INJECT = "from typing import ClassVar, Final, Iterator, Literal, Never, NoReturn, TypeAlias, TypeGuard, overload"
|
|
253
|
+
_LITERALENUM_INJECT = "from literalenum import LiteralEnum, LiteralEnumMeta"
|
|
217
254
|
_FUTURE = "from __future__ import annotations"
|
|
218
255
|
|
|
219
256
|
|
|
@@ -250,10 +287,12 @@ def _normalize_imports(import_lines: list[str]) -> list[str]:
|
|
|
250
287
|
continue
|
|
251
288
|
if s.startswith("from literalenum import") and "LiteralEnum" in s:
|
|
252
289
|
continue
|
|
290
|
+
if s.startswith("from types import") and "MappingProxyType" in s:
|
|
291
|
+
continue
|
|
253
292
|
if s.startswith("from typing import"):
|
|
254
293
|
# drop any typing line that imports our injected symbols
|
|
255
294
|
# (simple heuristic: if it mentions any of them, drop it)
|
|
256
|
-
symbols = ["ClassVar", "Final", "
|
|
295
|
+
symbols = ["ClassVar", "Final", "Iterator", "Literal", "TypeGuard", "overload"]
|
|
257
296
|
if any(sym in s for sym in symbols):
|
|
258
297
|
continue
|
|
259
298
|
out.append(s)
|
|
@@ -319,6 +358,7 @@ def _render_adjacent_preserving_stub(module: str, enums: list[EnumInfo]) -> str:
|
|
|
319
358
|
out.append("\n")
|
|
320
359
|
|
|
321
360
|
# Inject what enum blocks need, exactly once
|
|
361
|
+
out.append(_TYPES_INJECT + "\n")
|
|
322
362
|
out.append(_TYPING_INJECT + "\n")
|
|
323
363
|
out.append(_LITERALENUM_INJECT + "\n\n")
|
|
324
364
|
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: literalenum
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.4.0
|
|
4
4
|
Summary: A Python typing construct that provides namespaced literal constants with advanced typing features.
|
|
5
5
|
Project-URL: Homepage, https://github.com/modularizer/literalenum
|
|
6
6
|
Project-URL: Repository, https://github.com/modularizer/literalenum
|
|
@@ -12,8 +12,6 @@ Keywords: python,typehinting
|
|
|
12
12
|
Requires-Python: >=3.10
|
|
13
13
|
Description-Content-Type: text/markdown
|
|
14
14
|
|
|
15
|
-
from sample_str_enum_solutions.a_strenum import HttpMethod
|
|
16
|
-
|
|
17
15
|
# LiteralEnum
|
|
18
16
|
|
|
19
17
|
**LiteralEnum** is an experiment/prototype for a proposed Python typing construct:
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
literalenum/__init__.py,sha256=Cle3alhK2TPqkjKZ6yEFB3_2yv-y0EwtdYUnbkRG_-s,477
|
|
2
2
|
literalenum/literal_enum.py,sha256=OfB73GCHeZ5G1cAz3EA99zzZsmQ6jtL3xx3AKK-XP-0,3907
|
|
3
3
|
literalenum/mypy_plugin.py,sha256=JExHoi8NP_QJI0eESRed3TdR3DxEVrj7qA6q-bhj3KU,11020
|
|
4
|
-
literalenum/stubgen.py,sha256=
|
|
4
|
+
literalenum/stubgen.py,sha256=PdY4i_5eBHzQkOyMtctitreTtR-3lNOqrLqPocsCZ1g,17544
|
|
5
5
|
literalenum/compatibility_extensions/__init__.py,sha256=nIY32idsLpo9VyXtDREWMzLAfYUU7K7Zm3Cl69mWR0k,551
|
|
6
6
|
literalenum/compatibility_extensions/annotated.py,sha256=68TxWaCzMdcuFgnyWfWHUtzUClP5r99BMydSufdgcRA,146
|
|
7
7
|
literalenum/compatibility_extensions/bare_class.py,sha256=LXhT5BfIBJmfA8ZQmHfAVyF4IpM9911oUcj4xtonLFM,75
|
|
@@ -18,10 +18,10 @@ literalenum/compatibility_extensions/regex.py,sha256=4XDtC8VlehMlcZkcE5L9nXbKkR4
|
|
|
18
18
|
literalenum/compatibility_extensions/sqlalchemy_enum.py,sha256=DF_ce3Q7YNp98mTFXPsyWagQVzTTaczI-dRklOPh_LY,237
|
|
19
19
|
literalenum/compatibility_extensions/str_enum.py,sha256=y-VWFyaEDXmNicgyqzdEpsx-ImUdnydbF_YWhzvEVq0,329
|
|
20
20
|
literalenum/compatibility_extensions/strawberry_enum.py,sha256=mjg3Pyy0w_AggRRB_UtuWQiOguiG66eTN5E_rpwd7cg,526
|
|
21
|
-
typing_literalenum.py,sha256=
|
|
21
|
+
typing_literalenum.py,sha256=CKU4EBfMDZisrK8d9exWwp6sJhznJYp998oaRM5Igjs,27936
|
|
22
22
|
literalenum/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
23
|
-
literalenum-0.
|
|
24
|
-
literalenum-0.
|
|
25
|
-
literalenum-0.
|
|
26
|
-
literalenum-0.
|
|
27
|
-
literalenum-0.
|
|
23
|
+
literalenum-0.4.0.dist-info/METADATA,sha256=JA3sd54K2v5bhuOxtfnVroNnsGVajcRQeNMJ9fFzpVI,4819
|
|
24
|
+
literalenum-0.4.0.dist-info/WHEEL,sha256=WLgqFyCfm_KASv4WHyYy0P3pM_m7J5L9k2skdKLirC8,87
|
|
25
|
+
literalenum-0.4.0.dist-info/entry_points.txt,sha256=AK8je10LoLMOXuWLjXSqHV2rsTxPW9HlG7YTJGfwkCY,46
|
|
26
|
+
literalenum-0.4.0.dist-info/licenses/LICENSE,sha256=tQZYOMusRS38hVum5uAxSBrSxoQG9w0h6tkyE3RlPmw,1212
|
|
27
|
+
literalenum-0.4.0.dist-info/RECORD,,
|
typing_literalenum.py
CHANGED
|
@@ -370,6 +370,48 @@ class LiteralEnumMeta(type):
|
|
|
370
370
|
for names in cls._value_names_.values()
|
|
371
371
|
})
|
|
372
372
|
|
|
373
|
+
@property
|
|
374
|
+
def name_mapping(cls) -> Mapping[Any, str]:
|
|
375
|
+
"""A read-only ``{value: canonical_name}`` inverse mapping.
|
|
376
|
+
|
|
377
|
+
Each unique value maps to its first-declared (canonical) name::
|
|
378
|
+
|
|
379
|
+
class Method(LiteralEnum):
|
|
380
|
+
GET = "GET"
|
|
381
|
+
get = "GET" # alias
|
|
382
|
+
|
|
383
|
+
Method.name_mapping # {"GET": "GET"}
|
|
384
|
+
|
|
385
|
+
See also :attr:`names_mapping` for all names including aliases.
|
|
386
|
+
"""
|
|
387
|
+
return MappingProxyType({
|
|
388
|
+
v: names[0]
|
|
389
|
+
for v, names in zip(cls._ordered_values_, cls._value_names_.values())
|
|
390
|
+
})
|
|
391
|
+
|
|
392
|
+
@property
|
|
393
|
+
def names_by_value(cls) -> Mapping[Any, str]:
|
|
394
|
+
return cls.name_mapping
|
|
395
|
+
|
|
396
|
+
|
|
397
|
+
@property
|
|
398
|
+
def names_mapping(cls) -> Mapping[Any, tuple[str, ...]]:
|
|
399
|
+
"""A read-only ``{value: (name, ...)}`` inverse mapping.
|
|
400
|
+
|
|
401
|
+
Each unique value maps to a tuple of all its declared names
|
|
402
|
+
(canonical first, then aliases)::
|
|
403
|
+
|
|
404
|
+
class Method(LiteralEnum):
|
|
405
|
+
GET = "GET"
|
|
406
|
+
get = "GET" # alias
|
|
407
|
+
|
|
408
|
+
Method.names_mapping # {"GET": ("GET", "get")}
|
|
409
|
+
"""
|
|
410
|
+
return MappingProxyType({
|
|
411
|
+
v: names
|
|
412
|
+
for v, names in zip(cls._ordered_values_, cls._value_names_.values())
|
|
413
|
+
})
|
|
414
|
+
|
|
373
415
|
def keys(cls) -> tuple[str, ...]:
|
|
374
416
|
"""Return canonical member names in definition order (aliases excluded)."""
|
|
375
417
|
return tuple(
|
|
@@ -609,6 +651,62 @@ class LiteralEnumMeta(type):
|
|
|
609
651
|
"""
|
|
610
652
|
return validate_is_member(cls, x)
|
|
611
653
|
|
|
654
|
+
# ---- Testing utilities ----
|
|
655
|
+
|
|
656
|
+
def matches_enum(cls, enum_cls: type) -> bool:
|
|
657
|
+
"""Check whether this LiteralEnum has exactly the same values as *enum_cls*.
|
|
658
|
+
|
|
659
|
+
Compares the set of unique values in this LiteralEnum against the
|
|
660
|
+
``.value`` of every member in the given ``enum.Enum`` (or subclass).
|
|
661
|
+
Useful in test suites to assert two parallel definitions stay in sync::
|
|
662
|
+
|
|
663
|
+
import enum
|
|
664
|
+
|
|
665
|
+
class Color(enum.StrEnum):
|
|
666
|
+
RED = "red"
|
|
667
|
+
GREEN = "green"
|
|
668
|
+
|
|
669
|
+
class ColorLE(LiteralEnum):
|
|
670
|
+
RED = "red"
|
|
671
|
+
GREEN = "green"
|
|
672
|
+
|
|
673
|
+
assert ColorLE.matches_enum(Color)
|
|
674
|
+
|
|
675
|
+
Returns:
|
|
676
|
+
``True`` if the value sets are identical.
|
|
677
|
+
"""
|
|
678
|
+
try:
|
|
679
|
+
enum_values = {m.value for m in enum_cls}
|
|
680
|
+
except TypeError:
|
|
681
|
+
return False
|
|
682
|
+
return set(cls._ordered_values_) == enum_values
|
|
683
|
+
|
|
684
|
+
def matches_literal(cls, literal_type: Any) -> bool:
|
|
685
|
+
"""Check whether this LiteralEnum has exactly the same values as *literal_type*.
|
|
686
|
+
|
|
687
|
+
Extracts the arguments from a ``typing.Literal[...]`` and compares
|
|
688
|
+
them against this LiteralEnum's unique values. Useful in test suites
|
|
689
|
+
to assert a Literal type alias stays in sync with a LiteralEnum::
|
|
690
|
+
|
|
691
|
+
from typing import Literal
|
|
692
|
+
|
|
693
|
+
ColorLiteral = Literal["red", "green"]
|
|
694
|
+
|
|
695
|
+
class Color(LiteralEnum):
|
|
696
|
+
RED = "red"
|
|
697
|
+
GREEN = "green"
|
|
698
|
+
|
|
699
|
+
assert Color.matches_literal(ColorLiteral)
|
|
700
|
+
|
|
701
|
+
Returns:
|
|
702
|
+
``True`` if the value sets are identical.
|
|
703
|
+
"""
|
|
704
|
+
from typing import get_args
|
|
705
|
+
args = get_args(literal_type)
|
|
706
|
+
if not args:
|
|
707
|
+
return False
|
|
708
|
+
return set(cls._ordered_values_) == set(args)
|
|
709
|
+
|
|
612
710
|
|
|
613
711
|
# ---------------------------------------------------------------------------
|
|
614
712
|
# Base class
|
|
File without changes
|
|
File without changes
|
|
File without changes
|