pllopis / straw

Straw - The simple tool to suck the config out of your Slurm beverage!
BSD 3-Clause "New" or "Revised" License
10 stars 2 forks source link

Use default_factory to create default Header instances for SlurmMessage fields #3

Open zcrisler opened 1 year ago

zcrisler commented 1 year ago

SlurmMessage.header and SlurmMessage.auth fields need to use default_factory to initialize Header instances.

Using Python 3.11.3, simply importing the straw module shows the problem:

Python 3.11.3 (main, Apr  5 2023, 22:33:13) [GCC 10.2.1 20210110] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import straw
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python3.11/site-packages/straw.py", line 82, in <module>
    @dataclass
     ^^^^^^^^^
  File "/usr/local/lib/python3.11/dataclasses.py", line 1223, in dataclass
    return wrap(cls)
           ^^^^^^^^^
  File "/usr/local/lib/python3.11/dataclasses.py", line 1213, in wrap
    return _process_class(cls, init, repr, eq, order, unsafe_hash,
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.11/dataclasses.py", line 958, in _process_class
    cls_fields.append(_get_field(cls, name, type, kw_only))
                      ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.11/dataclasses.py", line 815, in _get_field
    raise ValueError(f'mutable default {type(f.default)} for field '
ValueError: mutable default <class 'straw.Header'> for field header is not allowed: use default_factory

Following the guidance in the ValueError, using default_factory appears to resolve the issue:

diff --git a/straw.py b/straw.py
index ebfe6fb..31c39cb 100644
--- a/straw.py
+++ b/straw.py
@@ -90,8 +90,8 @@ class SlurmMessage:
     """
     data: bytes = None

-    header: Header = Header()
-    auth: Auth = Header()
+    header: Header = field(default_factory=Header)
+    auth: Auth = field(default_factory=Header)
     body: Body = None

     _unpack_offset: int = 0

With the fix, the import succeeds:

Python 3.11.3 (main, Apr  5 2023, 22:33:13) [GCC 10.2.1 20210110] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import straw
>>> 
pllopis commented 1 year ago

Thank you! Diff looks good to me. Do you want to make a PR (to reflect your contribution) or do you prefer me to commit directly?