Skip to content

Commit 1000610

Browse files
agnerspull[bot]
authored andcommitted
[python] Fix Cluster objects datatypes on Python 3.11 (#26729)
* [python] Fix Cluster objects datatypes on Python 3.11 It seems that Python 3.11 requires the custom data type Nullable to implement the __hash__() function, otherwise initializing dataclass annotated objects fail with the following stack trace: ``` File "/home/sag/projects/project-chip/connectedhomeip-v1.1/.environment/pigweed-venv/lib/python3.11/site-packages/chip/clusters/Objects.py", line 385, in Commands @DataClass ^^^^^^^^^ File "/usr/lib/python3.11/dataclasses.py", line 1223, in dataclass return wrap(cls) ^^^^^^^^^ File "/usr/lib/python3.11/dataclasses.py", line 1213, in wrap return _process_class(cls, init, repr, eq, order, unsafe_hash, ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/lib/python3.11/dataclasses.py", line 958, in _process_class cls_fields.append(_get_field(cls, name, type, kw_only)) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/lib/python3.11/dataclasses.py", line 815, in _get_field raise ValueError(f'mutable default {type(f.default)} for field ' ValueError: mutable default <class 'chip.clusters.Types.Nullable'> for field capacity is not allowed: use default_factory ``` Since all instances of Nullable are the same "value", we can return a static 0 as hash value. * [python] Mark Nullable type frozen * address linter error * Revert dataclass frozen * Add comment
1 parent 031b93a commit 1000610

File tree

1 file changed

+8
-1
lines changed
  • src/controller/python/chip/clusters

1 file changed

+8
-1
lines changed

src/controller/python/chip/clusters/Types.py

+8-1
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,6 @@
1515
# limitations under the License.
1616
#
1717

18-
1918
class Nullable():
2019
def __repr__(self):
2120
return 'Null'
@@ -32,5 +31,13 @@ def __ne__(self, other):
3231
def __lt__(self, other):
3332
return True
3433

34+
def __hash__(self):
35+
''' Explicitly implement __hash__() to imply immutability when used in
36+
dataclasses.
37+
38+
See also: https://docs.python.org/3/library/dataclasses.html#dataclasses.dataclass
39+
'''
40+
return 0
41+
3542

3643
NullValue = Nullable()

0 commit comments

Comments
 (0)