allow constructor customization of complex enum variants
This is an (experimental) idea I had to support customization of the macro generated constructors for complex enum variants.
This allow placing the the #[pyo3(signature = ...)] attribute on complex enum variants and applies it to the generated constructor.
This way all the normal functionality of signature customization can also be applied for these generated constructors.
What I'm not completely sure about is whether we should reuse the signature name here, or whether we should have have some kind of alias like #[pyo3(constructor = ...)]. On one hand people are already familiar with how signature works, but using it on an enum variant (or anything that's not a function for that matter) is not so intuitive.
Closes #4109
I like this idea! I'll try to review the full code tomorrow, though I have some initial thoughts about how this extends:
- it would be awesome to support something like this for
#[pyclass]to automatically generate the#[new]in that case too. Issignaturethe right name in that case? I feel likeconstructor,new, or eveninitmight be stronger choices when it's adding a function to the class? - re
signaturevsconstructor, the only conflict I can think of is that we might want to allow users to do something likeconstructor = "some_func"in cases where the auto-generated constructor isn't enough. Or maybe we should have#[new(MyVariant)]in#[pymethods]for that case, if that's technically viable?
- it would be awesome to support something like this for
#[pyclass]to automatically generate the#[new]in that case too. Issignaturethe right name in that case?
Yeah, that came up in https://github.com/PyO3/pyo3/issues/4109#issuecomment-2082181122 too. I think that extension is a good argument to go with a more descriptive keyword for that context.
- re
signaturevsconstructor, the only conflict I can think of is that we might want to allow users to do something likeconstructor = "some_func"
Hmm, interesting idea. It might be pretty tricky to guarantee that the correct variant is constructed if we open this for users.
- re
signaturevsconstructor, the only conflict I can think of is that we might want to allow users to do something likeconstructor = "some_func"Hmm, interesting idea. It might be pretty tricky to guarantee that the correct variant is constructed if we open this for users.
Ah, very true, I guess we probably cannot, which is a good reason not to add that. And they can always add their own #[staticmethod] or #[classmethod] which constructs the variants anyway.
I've added to the complex enum section of the guide and put the attribute in the pyclass options table. Is there any other place where we want to mention this?
@davidhewitt, @Icxolu thank you for implementing this!