python-attrs / python-attrs/attrs

Make parent class initalization easy

Open
#507 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

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

Description

In some cases it is useful to create an new object by copying some of the attributes that are provided by a shared base class. Here is an example

import attr

@attr.s()
class Base(object):
    uid = attr.ib()
    name = attr.ib()
    
@attr.s()
class AreaChild(Base):
    area = attr.ib()
    
@attr.s()
class LengthChild(Base):
    length = attr.ib()
    
def calc_square(length_obj):
    def make_class_filter(cls):
        cls_fields = attr.fields_dict(cls)
        return lambda a,v: a.name in cls_fields

    base_dict = attr.asdict(length_obj, 
                            filter = make_class_filter(Base))
    
    return AreaChild(area = length_obj.length**2, 
                     **base_dict)

lc = LengthChild(uid=42, name='rope', length=3)
print(lc)
ac = calc_square(lc)
print(ac)

As one can see extraction of the base class attributes is somewhat clunky. The calc_square function could be much easier to read if a base class could be passed as a filter to .asdict:

def calc_square(length_obj):
    base_dict = attr.asdict(length_obj, filter = Base)
    return AreaChild(area=length_obj.length**2, **base_dict)

If you would think this makes sense, I could provide a pull request to enable classes as filters with the functionality as described above.

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.

Research direction

Start by reviewing attrs.asdict and its existing filter behavior, using the Base, LengthChild, and AreaChild example in the issue as the reference case. The work is done when a class such as Base can be passed directly as the filter and produces the same base-attribute dictionary shown in the example, with coverage for that behavior.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
developer-experience
Issue type
Feature
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.