Skip to content

Make parent class initalization easy #507

@deniz195

Description

@deniz195

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions