literalenum 0.2.0__py3-none-any.whl → 0.3.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 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
- alias = f"{e.name}T"
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"{alias}: TypeAlias = Literal[{literal_union}]\n\n")
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
- out.append(f" T_ = Literal[{literal_union}]\n")
145
- if not own_members:
146
- out.append(" ...\n")
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
- out.append(f" values: ClassVar[Iterable[{alias}]]\n")
152
- out.append(f" mapping: ClassVar[dict[str, {alias}]]\n\n")
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: {alias}) -> {alias}: ...\n")
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) -> {alias}: ...\n\n")
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 typing import ClassVar, Final, Literal, Iterable, Never, NoReturn, TypeGuard, TypeAlias, overload\n")
206
- out.append("from literalenum import LiteralEnum\n\n")
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
- _TYPING_INJECT = "from typing import ClassVar, Final, Literal, Iterable, Never, NoReturn, TypeGuard, TypeAlias, overload"
216
- _LITERALENUM_INJECT = "from literalenum import LiteralEnum"
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", "Literal", "Iterable", "TypeGuard", "overload"]
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.2.0
3
+ Version: 0.3.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=IWT774iThGrbXkYOjVcoCd8Osst9InXpwUJvb3EcG4I,15654
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=ZoM0rbr-7Hp72uqohJ6enm-eIhUwAHTGBsb-FsQmXJs,24837
21
+ typing_literalenum.py,sha256=eIhM_dGUR9Eu1PqQr78wKk0CH_IUUIS6cy1_pPEkPss,26653
22
22
  literalenum/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
23
- literalenum-0.2.0.dist-info/METADATA,sha256=2f2bFRLze4cbkzhiL5xogmz_vJyQU4Rqwd_B-PtqOd4,4879
24
- literalenum-0.2.0.dist-info/WHEEL,sha256=WLgqFyCfm_KASv4WHyYy0P3pM_m7J5L9k2skdKLirC8,87
25
- literalenum-0.2.0.dist-info/entry_points.txt,sha256=AK8je10LoLMOXuWLjXSqHV2rsTxPW9HlG7YTJGfwkCY,46
26
- literalenum-0.2.0.dist-info/licenses/LICENSE,sha256=tQZYOMusRS38hVum5uAxSBrSxoQG9w0h6tkyE3RlPmw,1212
27
- literalenum-0.2.0.dist-info/RECORD,,
23
+ literalenum-0.3.0.dist-info/METADATA,sha256=r6KARro6c4xHELgYgAkQighvv6Qv3E54aHtG5xmuOj4,4819
24
+ literalenum-0.3.0.dist-info/WHEEL,sha256=WLgqFyCfm_KASv4WHyYy0P3pM_m7J5L9k2skdKLirC8,87
25
+ literalenum-0.3.0.dist-info/entry_points.txt,sha256=AK8je10LoLMOXuWLjXSqHV2rsTxPW9HlG7YTJGfwkCY,46
26
+ literalenum-0.3.0.dist-info/licenses/LICENSE,sha256=tQZYOMusRS38hVum5uAxSBrSxoQG9w0h6tkyE3RlPmw,1212
27
+ literalenum-0.3.0.dist-info/RECORD,,
typing_literalenum.py CHANGED
@@ -609,6 +609,62 @@ class LiteralEnumMeta(type):
609
609
  """
610
610
  return validate_is_member(cls, x)
611
611
 
612
+ # ---- Testing utilities ----
613
+
614
+ def matches_enum(cls, enum_cls: type) -> bool:
615
+ """Check whether this LiteralEnum has exactly the same values as *enum_cls*.
616
+
617
+ Compares the set of unique values in this LiteralEnum against the
618
+ ``.value`` of every member in the given ``enum.Enum`` (or subclass).
619
+ Useful in test suites to assert two parallel definitions stay in sync::
620
+
621
+ import enum
622
+
623
+ class Color(enum.StrEnum):
624
+ RED = "red"
625
+ GREEN = "green"
626
+
627
+ class ColorLE(LiteralEnum):
628
+ RED = "red"
629
+ GREEN = "green"
630
+
631
+ assert ColorLE.matches_enum(Color)
632
+
633
+ Returns:
634
+ ``True`` if the value sets are identical.
635
+ """
636
+ try:
637
+ enum_values = {m.value for m in enum_cls}
638
+ except TypeError:
639
+ return False
640
+ return set(cls._ordered_values_) == enum_values
641
+
642
+ def matches_literal(cls, literal_type: Any) -> bool:
643
+ """Check whether this LiteralEnum has exactly the same values as *literal_type*.
644
+
645
+ Extracts the arguments from a ``typing.Literal[...]`` and compares
646
+ them against this LiteralEnum's unique values. Useful in test suites
647
+ to assert a Literal type alias stays in sync with a LiteralEnum::
648
+
649
+ from typing import Literal
650
+
651
+ ColorLiteral = Literal["red", "green"]
652
+
653
+ class Color(LiteralEnum):
654
+ RED = "red"
655
+ GREEN = "green"
656
+
657
+ assert Color.matches_literal(ColorLiteral)
658
+
659
+ Returns:
660
+ ``True`` if the value sets are identical.
661
+ """
662
+ from typing import get_args
663
+ args = get_args(literal_type)
664
+ if not args:
665
+ return False
666
+ return set(cls._ordered_values_) == set(args)
667
+
612
668
 
613
669
  # ---------------------------------------------------------------------------
614
670
  # Base class