Skip to content

cattr.structure isn't working for classes uncluding dicts #151

@Natanela

Description

@Natanela
  • cattrs version: 1.7.1 (attrs-21.2.0 cattrs-1.7.1)
  • Python version: 3.8.1
  • Operating System: both Windows 10 and Linux

Description

I'm trying to structure a JSON file into a class defined with attrs.

Here is my class definition:

@attr.s(frozen=True, auto_attribs=True)
class SchedulingDefinition:
    schedule: str = attr.ib()
    job_name: str = attr.ib(default=attr.Factory(lambda self: self.notebook_name, takes_self=True))
    job_id: str = attr.ib(default=attr.Factory(lambda: hashlib.sha224(uuid.uuid4().bytes).hexdigest()[:10]))
    timeout_in_min: int = 60
    retry_count: int = 1
    parameters: Optional[Dict] = attr.ib(default=None)

I'm using the following line to destructure the JSON file:

    with open(os.path.join(scheduling_definitions_dir, scheduling_definition_file), 'rb') as f:
            definition = cattr.structure(json.load(f), SchedulingDefinition)

JSON files that contain a parameters property fail with the following error message:
Unsupported type: ~KT. Register a structure hook for it.

here is the full trace:

File "./scheduling.py", line 170, in load_scheduling_definitions
  definition = cattr.structure(json.load(f), SchedulingDefinition)
File "/opt/hostedtoolcache/Python/3.7.10/x64/lib/python3.7/site-packages/cattr/converters.py", line 223, in structure
  return self._structure_func.dispatch(cl)(obj, cl)
File "", line 17, in structure_SchedulingDefinition
File "/opt/hostedtoolcache/Python/3.7.10/x64/lib/python3.7/site-packages/cattr/converters.py", line 439, in _structure_union
  return self._structure_func.dispatch(other)(obj, other)
File "", line 2, in structure_mapping
File "", line 2, in <dictcomp>
File "/opt/hostedtoolcache/Python/3.7.10/x64/lib/python3.7/site-packages/cattr/converters.py", line 304, in _structure_default
  raise ValueError(msg)

ValueError: Unsupported type: ~KT. Register a structure hook for it.

Here is an example JSON input file which fails to structure:

{
    "schedule": "0 15 8 ? * * *",
    "job_name": "Backfill",
    "job_id": "602608e0c9",
    "timeout_in_min": 60,
    "retry_count": 1,
    "parameters": {
        "days_back": 90,
        "shard_size": "2D"
    }
}

This logic worked perfectly fine up until v1.6.0 (included) but started to fail on 1.7.0 and 1.7.1

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions