attrs icon indicating copy to clipboard operation
attrs copied to clipboard

Combine multiple classes

Open dkrikun opened this issue 11 months ago • 6 comments

Is it possible to combine two (or more) class declarations into one? This should be similar to multiple inheritance I guess, but should work with slots.

For example:

@define
class Point2d:
    x : int
    y : int

@define
class Line:
    start : Point2d
    end : Point2d
    
@define
class StrokeProperties:
     size : float
     color : Color
     
DrawnPoint = some_magic(Point2d, StrokeProperties)
DrawnLine = some_magic(Line, StrokeProperties)

print(DrawnPoint.x, DrawnPoint.size)

One could argue, that composition should be used instead, but I think it could be nicer to be able to access attributes without nesting.

Is there something like this in attrs, or how it could be done using existing api?

dkrikun avatar Jan 05 '25 16:01 dkrikun

@dkrikun Given that Hynek doesn't reaaallly like make_class(), I doubt that something like this will be added. In addition, you'd have to work out a conflict resolution strategy for the case that two classes define the same attributes.

On the other hand, you can relatively easily write your own function that combines the fields of two attrs classes and passes them to make_class().

I did something similar for Typed Settings, maybe you can just copy and adjust this code (which was handcrafted by a real human): https://gitlab.com/sscherfke/typed-settings/-/blob/24.6.0/src/typed_settings/cls_attrs.py?ref_type=tags#L387-487 ;-)

sscherfke avatar Jan 05 '25 18:01 sscherfke

Gotta enjoy the human part while it still exists, thanks ;)

dkrikun avatar Jan 05 '25 18:01 dkrikun

Another problem here is that there's currently no way to make this in any way work with type checkers.

So merging a feature like this to attrs proper would only add another cause for a flurry of issues about PyCharm/Pyright/Mypy complaining and us not being able to do anything about it at all.

hynek avatar Jan 06 '25 07:01 hynek

Is there any fundamental reason against make_class()? Because it would seem to me that in general it could be a nice thing to have a functional api to do all kinds of things with "datalclass" definitions: combine, extract, nest, replace fields, etc.?

dkrikun avatar Jan 09 '25 11:01 dkrikun

It depends on you whether or not you find it fundamental, but the types returned by make_class are considered of type Any and given the dynamics in the typing ecosystem (nothing gets implemented unless someone writes a PEP), I don't think this will ever change.

hynek avatar Jan 12 '25 05:01 hynek

Html

PatelNikhil666 avatar Jul 21 '25 07:07 PatelNikhil666