python-attrs / python-attrs/attrs
Eliminate evolve() boilerplate with evolvers/copy
Nobody has claimed this yet.
- Dominant language
- Python
- Stars
- 5.8k
- Forks
- 480
- Avg merge
- 2h 15m
- Merged PRs (30d)
- 2
Description
When I want to evolve() an object, I sometimes have to do a bit of boilerplate copy()ing:
from typing import List
import attr
@attr.s
class Car:
model: str = attr.ib()
occupants: List = attr.ib()
car1 = Car("Toyota", ["Alice", "Bob"])
car2 = attr.evolve(car1, model="Honda", occupants=car1.occupants.copy())
To eliminate this boilerplate, one option would be:
@attr.s
class Car:
model: str = attr.ib()
occupants: List = attr.ib(evolver=lambda x: x.copy())
Or similarly:
@attr.s
class Car:
model: str = attr.ib()
occupants: List = attr.ib()
@occupants
def evolver(self):
return self.occupants.copy()
Or using copy.copy() via the __copy__ method:
@attr.s
class Car:
model: str = attr.ib()
occupants: List = attr.ib(evolve_copy=True)
The latter idea suggests the option of putting the copy functionality into @attr.s, which could add a __copy__ method to the class, and like the other methods it could be enabled/disabled for each attribute with attr.ib(copy=True/False), and evolve() could use copy.copy() by default.
@attr.s(copy=True)
class Car:
model: str = attr.ib()
occupants: List = attr.ib()
components: pyrsistent.PSet = attr.ib(copy=False)
cc: @altendky
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start by reviewing the existing evolve(), attr.s, and attr.ib behavior described in the issue, then compare the proposed evolver, decorator, and copy approaches. The issue does not name implementation files or tests; the work is done when one agreed API is specified, implemented, and covered by tests for copied and non-copied attributes.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python
- Domain
- tooling
- Issue type
- Feature
- Difficulty
- 5/5
- Estimated time
- Over a week
- Activity status
- Stale
- Clarity
- Needs clarification
- Newbie friendliness
- 25/100