pyo3 icon indicating copy to clipboard operation
pyo3 copied to clipboard

Allowing `type`s to define Python classes

Open somehybrid opened this issue 10 months ago • 4 comments

Currently, the only way to create a Python class is with a struct. However, using a type to define a class could remove a lot of boilerplate from creating similar classes.

somehybrid avatar Oct 16 '23 00:10 somehybrid

Do you mean a Rust type? Since these are just aliases, not actual separate types, I don't see how this could work.

birkenfeld avatar Oct 16 '23 17:10 birkenfeld

I think one thing were that might be useful would be generics, i.e. use type to name multiple instantiations which should become classes. Not sure how the methods would be handled generically though.

adamreichold avatar Oct 16 '23 18:10 adamreichold

I think that for something like

#[pyclass] 
type Foo = i32;

We won't be able to implement PyClass for i32, so PyO3 would need to create some hidden struct and implement the traits for that. Would that be a problem? I don't know, it would be a bit... magical.

Otherwise, this only works for type Foo = X where X is also defined in the same crate.

Further, this breaks the ability for us to parse any struct fields or enum variants, so I guess we'd have to just treat this as an opaque type (which could have methods, maybe).

I think one thing were that might be useful would be generics, i.e. use type to name multiple instantiations which should become classes. Not sure how the methods would be handled generically though.

That's an interesting thought. I suppose in this case we'd have #[pyclass] on the generic and then require actual instantiations? It's an interesting question.

davidhewitt avatar Oct 16 '23 19:10 davidhewitt

My idea was kind of doing something like

#[pyclass]
type Something = MyClass<something_else>

where MyClass would be a #[pyclass]ed struct

somehybrid avatar Oct 18 '23 10:10 somehybrid