pyo3
pyo3 copied to clipboard
feature suggestion: extending PyTuple
Right now it is impossible to
#[pyclass(extends=PyTuple)]
struct Bla {
// ...
}
I'd like to do that to get a rust namedtuple like class.
What would that entail?
At the moment this is disabled because we weren't confident that subclassing PyTuple would work correctly.
The complexity is during __new__ implementation. A subclass of PyTuple needs to pass the number of items in the tuple up to the PyTuple base class, which we don't do correctly right now. In addition, the items are laid out in memory after the main class data. This shouldn't be a problem, but we weren't sure.
I actually have a patch which might tentatively fix the above (among with some other problems). If you give me a few days, I'll try to push that patch and cc you. Once it works, we can try subclassing PyTuple and see whether we can make it work.
Sounds good, thanks.
On Tue, Jun 1, 2021 at 9:13 PM David Hewitt @.***> wrote:
At the moment this is disabled because we weren't confident that subclassing PyTuple would work correctly.
The complexity is during new implementation. A subclass of PyTuple needs to pass the number of items in the tuple up to the PyTuple base class, which we don't do correctly right now. In addition, the items are laid out in memory after the main class data. This shouldn't be a problem, but we weren't sure.
I actually have a patch which might tentatively fix the above (among with some other problems). If you give me a few days, I'll try to push that patch and cc you. Once it works, we can try subclassing PyTuple and see whether we can make it work.
— You are receiving this because you authored the thread. Reply to this email directly, view it on GitHub https://github.com/PyO3/pyo3/issues/1647#issuecomment-852341755, or unsubscribe https://github.com/notifications/unsubscribe-auth/ASHRLMPOXW7OKIA5J55GPLLTQUPOPANCNFSM454HPREQ .
As an alternative, for the specific case of creating namedtuple-like classes, you could look at using PyStructSequence under the hood.
This is what CPython uses internally to create sys.version_info, for example.
From the docs:
Struct sequence objects are the C equivalent of namedtuple() objects, i.e. a sequence whose items can also be accessed through attributes.