open-enum 0.1.0__tar.gz

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.
@@ -0,0 +1,132 @@
1
+ Metadata-Version: 2.3
2
+ Name: open-enum
3
+ Version: 0.1.0
4
+ Summary: Add your description here
5
+ Requires-Python: >=3.12
6
+ Description-Content-Type: text/markdown
7
+
8
+ # OpenEnum
9
+
10
+ Enum implementation that accepts unknown values.
11
+
12
+ ## Rationale
13
+
14
+ When parsing external data into Python data types, sometimes we deal with enumerated data types which have several documented possible values, but should be parsed with assumption that more possible values will be added over time.
15
+
16
+ Code that reads such values should be written with **forward compatibility** in mind: handle all known values, but also include a fallback for any other values that can appear in the future. Options for doing this in Python include parsing as `str`, as `EnumType | str` or as `EnumType` with a `_missing_` method defined.
17
+
18
+ This library attempts to provide a pattern for handling such values in a **type-safe manner that plays well with existing linters**.
19
+
20
+ ## Usage
21
+
22
+ ### Parsing possibly-unknown values
23
+
24
+ Define an `OpenEnum` subclass with one member value of `None` that will be used as fallback:
25
+
26
+ ```python
27
+ from open_enum import OpenEnum
28
+
29
+
30
+ class Status(OpenEnum):
31
+ NEW = "new"
32
+ IN_PROGRESS = "in_progress"
33
+ DONE = "done"
34
+
35
+ UNKNOWN = None
36
+ ```
37
+
38
+ Normal values work intuitively:
39
+
40
+ ```python
41
+ new = Status.NEW
42
+ done = Status.DONE
43
+ assert Status("new") == new
44
+ assert Status("new") != done
45
+ ```
46
+
47
+ But unlike normal enum, you can also instantiate the type with unknown values:
48
+
49
+ ```python
50
+ blocked = Status("blocked")
51
+ cancelled = Status("cancelled")
52
+ assert isinstance(blocked, Status)
53
+ ```
54
+
55
+ These compare as different to each other:
56
+
57
+ ```python
58
+ assert blocked != new
59
+ assert blocked != cancelled
60
+ ```
61
+
62
+ but still compare as equal if the underlying value matches:
63
+
64
+ ```python
65
+ assert blocked == Status("blocked")
66
+ ```
67
+
68
+ ### Checking for unknown values using the `UNKNOWN` marker
69
+
70
+ The `UNKNOWN` value defined on the enum type is a special **marker object**, not an actual enum member:
71
+
72
+ ```python
73
+ assert not isinstance(Status.UNKNOWN, Status)
74
+ ```
75
+
76
+ > [!NOTE]
77
+ > You'll never get `Status.UNKNOWN` from parsing; it's meant to be used explicitly.
78
+
79
+ The unknown marker compares as equal to unknown values, but not to known values:
80
+
81
+ ```python
82
+ assert Status.UNKNOWN == Status("blocked")
83
+ assert Status.UNKNOWN == Status("cancelled")
84
+
85
+ assert Status.UNKNOWN != Status("new")
86
+ assert Status.UNKNOWN != Status("in_progress")
87
+ ```
88
+
89
+ ### Pattern matching
90
+
91
+ All this allows you to do **exhaustive pattern matching** that your linter will validate for you:
92
+
93
+ ```python
94
+
95
+ class Response:
96
+ status: Status
97
+ ...
98
+
99
+
100
+ match response.status:
101
+ case Status.NEW:
102
+ print("new!")
103
+ case Status.IN_PROGRESS:
104
+ print("in progress...")
105
+ case Status.DONE:
106
+ print("nothing more to do")
107
+ case Status.UNKNOWN:
108
+ print("oh, encountered a status we don't know!")
109
+ case _:
110
+ assert_never(response.status)
111
+ ```
112
+
113
+ Now if you go back to `class Status` and add enum members for `"blocked"` or `"cancelled"`, your type checker will ask you to add corresponding `case` arms in this `match` statement.
114
+
115
+ > [!TIP]
116
+ > The main advantage of this pattern over just using `case _` as fallback is that is that it **communicates the intention that every known value should have a `case` branch**. Thanks to `assert_never`, a type checker can actually check and enforce this!
117
+
118
+ Importantly, as long as you include `assert_never`, the type checker should nudge you to include a case for `Status.UNKNOWN`:
119
+
120
+ ```python
121
+ match response.status:
122
+ case Status.NEW:
123
+ print("new!")
124
+ case Status.IN_PROGRESS:
125
+ print("in progress...")
126
+ case Status.DONE:
127
+ print("nothing more to do")
128
+ case _:
129
+ assert_never(response.status) # error: Type "Literal[Status.UNKNOWN]" is not assignable to type "Never"
130
+ ```
131
+
132
+ This way as long as you remember about `assert_never()`, you'll have a helpful reminder to add handling of additional unknown values that can be added in the future, even if you already handled all values that are _currently_ documented.
@@ -0,0 +1,125 @@
1
+ # OpenEnum
2
+
3
+ Enum implementation that accepts unknown values.
4
+
5
+ ## Rationale
6
+
7
+ When parsing external data into Python data types, sometimes we deal with enumerated data types which have several documented possible values, but should be parsed with assumption that more possible values will be added over time.
8
+
9
+ Code that reads such values should be written with **forward compatibility** in mind: handle all known values, but also include a fallback for any other values that can appear in the future. Options for doing this in Python include parsing as `str`, as `EnumType | str` or as `EnumType` with a `_missing_` method defined.
10
+
11
+ This library attempts to provide a pattern for handling such values in a **type-safe manner that plays well with existing linters**.
12
+
13
+ ## Usage
14
+
15
+ ### Parsing possibly-unknown values
16
+
17
+ Define an `OpenEnum` subclass with one member value of `None` that will be used as fallback:
18
+
19
+ ```python
20
+ from open_enum import OpenEnum
21
+
22
+
23
+ class Status(OpenEnum):
24
+ NEW = "new"
25
+ IN_PROGRESS = "in_progress"
26
+ DONE = "done"
27
+
28
+ UNKNOWN = None
29
+ ```
30
+
31
+ Normal values work intuitively:
32
+
33
+ ```python
34
+ new = Status.NEW
35
+ done = Status.DONE
36
+ assert Status("new") == new
37
+ assert Status("new") != done
38
+ ```
39
+
40
+ But unlike normal enum, you can also instantiate the type with unknown values:
41
+
42
+ ```python
43
+ blocked = Status("blocked")
44
+ cancelled = Status("cancelled")
45
+ assert isinstance(blocked, Status)
46
+ ```
47
+
48
+ These compare as different to each other:
49
+
50
+ ```python
51
+ assert blocked != new
52
+ assert blocked != cancelled
53
+ ```
54
+
55
+ but still compare as equal if the underlying value matches:
56
+
57
+ ```python
58
+ assert blocked == Status("blocked")
59
+ ```
60
+
61
+ ### Checking for unknown values using the `UNKNOWN` marker
62
+
63
+ The `UNKNOWN` value defined on the enum type is a special **marker object**, not an actual enum member:
64
+
65
+ ```python
66
+ assert not isinstance(Status.UNKNOWN, Status)
67
+ ```
68
+
69
+ > [!NOTE]
70
+ > You'll never get `Status.UNKNOWN` from parsing; it's meant to be used explicitly.
71
+
72
+ The unknown marker compares as equal to unknown values, but not to known values:
73
+
74
+ ```python
75
+ assert Status.UNKNOWN == Status("blocked")
76
+ assert Status.UNKNOWN == Status("cancelled")
77
+
78
+ assert Status.UNKNOWN != Status("new")
79
+ assert Status.UNKNOWN != Status("in_progress")
80
+ ```
81
+
82
+ ### Pattern matching
83
+
84
+ All this allows you to do **exhaustive pattern matching** that your linter will validate for you:
85
+
86
+ ```python
87
+
88
+ class Response:
89
+ status: Status
90
+ ...
91
+
92
+
93
+ match response.status:
94
+ case Status.NEW:
95
+ print("new!")
96
+ case Status.IN_PROGRESS:
97
+ print("in progress...")
98
+ case Status.DONE:
99
+ print("nothing more to do")
100
+ case Status.UNKNOWN:
101
+ print("oh, encountered a status we don't know!")
102
+ case _:
103
+ assert_never(response.status)
104
+ ```
105
+
106
+ Now if you go back to `class Status` and add enum members for `"blocked"` or `"cancelled"`, your type checker will ask you to add corresponding `case` arms in this `match` statement.
107
+
108
+ > [!TIP]
109
+ > The main advantage of this pattern over just using `case _` as fallback is that is that it **communicates the intention that every known value should have a `case` branch**. Thanks to `assert_never`, a type checker can actually check and enforce this!
110
+
111
+ Importantly, as long as you include `assert_never`, the type checker should nudge you to include a case for `Status.UNKNOWN`:
112
+
113
+ ```python
114
+ match response.status:
115
+ case Status.NEW:
116
+ print("new!")
117
+ case Status.IN_PROGRESS:
118
+ print("in progress...")
119
+ case Status.DONE:
120
+ print("nothing more to do")
121
+ case _:
122
+ assert_never(response.status) # error: Type "Literal[Status.UNKNOWN]" is not assignable to type "Never"
123
+ ```
124
+
125
+ This way as long as you remember about `assert_never()`, you'll have a helpful reminder to add handling of additional unknown values that can be added in the future, even if you already handled all values that are _currently_ documented.
@@ -0,0 +1,17 @@
1
+ [project]
2
+ name = "open-enum"
3
+ version = "0.1.0"
4
+ description = "Add your description here"
5
+ readme = "README.md"
6
+ requires-python = ">=3.12"
7
+ lincense = "MIT"
8
+ dependencies = []
9
+
10
+ [build-system]
11
+ requires = ["uv_build>=0.9.0,<0.10.0"]
12
+ build-backend = "uv_build"
13
+
14
+ [dependency-groups]
15
+ dev = [
16
+ "pytest>=8.4.2",
17
+ ]
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Tomasz Wesołowski
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ from .open_enum import OpenEnum as OpenEnum
@@ -0,0 +1,55 @@
1
+ from enum import Enum, EnumMeta
2
+ from typing import Type, cast
3
+
4
+
5
+ class OpenEnumMeta(EnumMeta):
6
+ def __new__(cls, name, bases, classdict):
7
+ # Only use the custom behavior for subclasses
8
+ if name == "OpenEnum" and bases == (Enum,):
9
+ return super().__new__(cls, name, bases, classdict)
10
+
11
+ # Find the None member in classdict
12
+ none_items = {k: v for k, v in classdict.items() if v is None}
13
+ if len(none_items) > 1:
14
+ raise ValueError("Only one None member is allowed in OpenEnum")
15
+ if len(none_items) == 0:
16
+ raise ValueError("An OpenEnum must have a None member")
17
+ (unknown_key,) = none_items.keys()
18
+
19
+ # Create a marker class for this specific enum
20
+ class UnknownMarker:
21
+ own_type: Type[Enum]
22
+ own_members: set[Enum]
23
+
24
+ def __eq__(self, other):
25
+ return (
26
+ isinstance(other, self.own_type) and other not in self.own_members
27
+ )
28
+
29
+ # make it not a memmber
30
+ classdict.pop(unknown_key)
31
+ classdict._member_names.pop(unknown_key)
32
+
33
+ # substitute the marker instad
34
+ classdict._ignore.append(unknown_key)
35
+ marker = UnknownMarker()
36
+ classdict[unknown_key] = marker
37
+ newcls = cast(Type[OpenEnum], super().__new__(cls, name, bases, classdict))
38
+
39
+ # configure the marker
40
+ marker.own_type = newcls
41
+ marker.own_members = set(newcls)
42
+
43
+ return newcls
44
+
45
+
46
+ class OpenEnum(Enum, metaclass=OpenEnumMeta):
47
+ @classmethod
48
+ def _missing_(cls, value):
49
+ instance = object.__new__(cls)
50
+ instance._name_ = "UNKNOWN"
51
+ instance._value_ = value
52
+ instance = cls._value2member_map_.setdefault(value, instance)
53
+ return instance
54
+
55
+ __match_args__ = ("value",)
@@ -0,0 +1,132 @@
1
+ from typing import assert_never
2
+ import pytest
3
+ from open_enum import OpenEnum
4
+
5
+
6
+ class Status(OpenEnum):
7
+ NEW = "new"
8
+ IN_PROGRESS = "in_progress"
9
+ DONE = "done"
10
+
11
+ UNKNOWN = None
12
+
13
+
14
+ # Known values
15
+ new = Status.NEW
16
+ done = Status.DONE
17
+
18
+ # Unknown values
19
+ blocked = Status("blocked")
20
+ cancelled = Status("cancelled")
21
+
22
+
23
+ def test_member_list():
24
+ assert list(Status) == [Status.NEW, Status.IN_PROGRESS, Status.DONE]
25
+
26
+
27
+ def test_basic_equality():
28
+ assert Status("new") == new
29
+ assert Status("new") != done
30
+
31
+
32
+ def test_subtyping():
33
+ assert isinstance(blocked, Status)
34
+
35
+
36
+ def test_value_equality():
37
+ assert blocked == Status("blocked")
38
+ assert blocked != new
39
+ assert blocked != cancelled
40
+
41
+
42
+ def test_unknown_subtyping():
43
+ assert not isinstance(Status.UNKNOWN, Status)
44
+
45
+
46
+ def test_unknown_equality():
47
+ assert Status.UNKNOWN == Status("blocked")
48
+ assert Status.UNKNOWN == Status("cancelled")
49
+ assert Status.UNKNOWN != Status("new")
50
+ assert Status.UNKNOWN != Status("in_progress")
51
+
52
+
53
+ @pytest.mark.parametrize(
54
+ "input,output",
55
+ [
56
+ ("new", "new"),
57
+ ("in_progress", "in progress"),
58
+ ("done", "done and done"),
59
+ ("cancelled", "unknown: cancelled"),
60
+ ("closed", "unknown: closed"),
61
+ ],
62
+ )
63
+ def test_pattern_matching_simple(input, output):
64
+ status = Status(input)
65
+
66
+ match status:
67
+ case Status.NEW:
68
+ result = "new"
69
+ case Status.IN_PROGRESS:
70
+ result = "in progress"
71
+ case Status.DONE:
72
+ result = "done and done"
73
+ case Status.UNKNOWN:
74
+ result = f"unknown: {status._value_}"
75
+ case _:
76
+ assert_never(status)
77
+
78
+ assert result == output
79
+
80
+
81
+ @pytest.mark.parametrize(
82
+ "input,output",
83
+ [
84
+ ("new", "known value"),
85
+ ("in_progress", "known value"),
86
+ ("done", "known value"),
87
+ ("cancelled", "custom value"),
88
+ ("blocked", "custom value"),
89
+ ("cursed", "unknown value"),
90
+ ],
91
+ )
92
+ def test_pattern_matching_multiple(input, output):
93
+ status = Status(input)
94
+
95
+ match status:
96
+ case Status.NEW | Status("in_progress") | Status.DONE:
97
+ result = "known value"
98
+ case Status("blocked") | Status("cancelled"):
99
+ result = "custom value"
100
+ case Status.UNKNOWN:
101
+ result = "unknown value"
102
+ case _:
103
+ assert_never(status)
104
+
105
+ assert result == output
106
+
107
+
108
+ def test_unknown_only_matches_own_type():
109
+ class Color(OpenEnum):
110
+ RED = "red"
111
+ GREEN = "green"
112
+
113
+ UNKNOWN = None
114
+
115
+ mauve = Color("mauve")
116
+ assert mauve == Color.UNKNOWN
117
+ assert mauve != Status.UNKNOWN
118
+
119
+ assert blocked == Status.UNKNOWN
120
+ assert blocked != Color.UNKNOWN
121
+
122
+ assert Color.UNKNOWN != Status.UNKNOWN
123
+
124
+
125
+ def test_custom_name_for_undefined():
126
+ class Color(OpenEnum):
127
+ RED = "red"
128
+ NOT_RED = None
129
+
130
+ mauve = Color("mauve")
131
+ assert mauve != Color.RED
132
+ assert mauve == Color.NOT_RED