asdict and astuple raise exceptions on instances with uninitialized attributes

Open
#677 2 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Assessment

Difficulty
3/5
Estimated time
1-2 days
Newbie friendliness
38/100
Issue type
Bug
Clarity
Mostly clear
Activity status
Stale
Tech stack
python
Domain
tooling

Research direction

Start by reproducing the provided TestClass example and inspect the attr.asdict and attr.astuple entry points. Check the existing serialization tests for instances with init=False attributes, then confirm the chosen behavior for an unset attribute is covered and that initialized attributes remain unchanged.

Written by the indexing model from the issue text.

Description

Feature

attrs 20.1.0, Python 3.8.3.

The asdict and astuple functions raise exceptions on instances with unset init=False attributes. I ran into this while looking into Tinche/cattrs#67, and was surprised to find attrs' serialization fails too. Consider the following code:

import attr

@attr.s
class TestClass:
    a = attr.ib()
    b = attr.ib(init=False)

x = TestClass(1)
# x.b = 2
print(x)
print(attr.asdict(x))

attr.astuple(x) raises an AttributeError as x.b is unset. However, it is reported fine by print(x) as TestClass(a=1, b=NOTHING). Uncommenting the line x.b = 2 fixes the problem.

Two alternatives I would suggest for dealing with this:

  1. Have the functions return attr.NOTHING for uninitialized attributes, and document this; or
  2. Document that these functions are invalid on such instances

I think (1) would be preferable, and I'm happy to submit a PR if that's wanted?

Dominant language
Python
Stars
5.8k
Forks
480
Avg merge
2h 15m
Merged PRs (30d)
2

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from python-attrs/attrs

All issues in python-attrs/attrs

Similar issues

More Python issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.