Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Combine multiple classes #1392

Open
dkrikun opened this issue Jan 5, 2025 · 4 comments
Open

Combine multiple classes #1392

dkrikun opened this issue Jan 5, 2025 · 4 comments

Comments

@dkrikun
Copy link

dkrikun commented Jan 5, 2025

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?

@sscherfke
Copy link
Contributor

sscherfke commented Jan 5, 2025

@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 ;-)

@dkrikun
Copy link
Author

dkrikun commented Jan 5, 2025

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

@hynek
Copy link
Member

hynek commented Jan 6, 2025

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants
@hynek @dkrikun @sscherfke and others