Skip to content

cattr.structure does not respect default value from attr.ib #10

@uhjish

Description

@uhjish
  • cattrs version: 0.40
  • Python version: 3.6.2
  • Operating System: Ubuntu 16.04 x86_64

Description

The attrs package allows default values for any given field, and allows initialisation of an attrs class without keys for which a default was provided.

With the following definition,

@attr.s(slots=True, frozen=True)
class Cfg(object):
    a = typed(int)
    b = typed(Optional[int])
    c = attr.ib(convert=int, default=7)
    d = typed(Optional[int], default=5)

We can instantiate a Cfg object as:

In [243]: Cfg(**dt)
Out[243]: Cfg(a=5, b=None, c=7, d=5)

When used with cattr.structure, however, the default values seem to be entirely ignored, moreover there is a KeyError exception thrown. While wrapping the attr.ib type in an Optional avoids the error, we wind up with None instead of the provided default value.

cattr.structure_attrs_fromdict({'a':5,'b':None}, Cfg)

In [208]: cattr.structure_attrs_fromdict(dt, Cfg)
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-208-5adc18822e6a> in <module>()
----> 1 cattr.structure_attrs_fromdict(dt, Cfg)

~/dev/survey_stats/venv/lib/python3.6/site-packages/cattr/converters.py in structure_attrs_fromdict(self, obj, cl)
    255             name = a.name
    256             # We detect the type by metadata.
--> 257             converted = self._structure_attr_from_dict(a, name, obj)
    258             conv_obj[name] = converted
    259

~/dev/survey_stats/venv/lib/python3.6/site-packages/cattr/converters.py in _structure_attr_from_dict(self, a, name, mapping)
    265         if type_ is None:
    266             # No type.
--> 267             return mapping[name]
    268         if isinstance(type_, _Union):
    269             # This is a union.

KeyError: 'c'

In [249]: cattr.structure_attrs_fromdict({'a':5,'b':None, 'c':3}, Cfg)
Out[249]: Cfg(a=5, b=None, c=3, d=None)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions