Subclasses and the builder pattern
Nobody has claimed this yet.
- Dominant language
- Rust
- Stars
- 16.2k
- Forks
- 1k
- Avg merge
- 2d 6h
- Merged PRs (30d)
- 66
Description
I have a python API implemented in rust that uses the builder pattern.
BaseClass is implemented in rust, and each subsequent method call creates a new BaseClass that is returned for method chaining. For example:
builder = BaseClass(context).event_1().event_2()
builder.activate()
I recently wanted to extend this pattern so I could have subclasses of BaseClass for specific implementation behaviors. The subclasses should use all the same builder functions from the BaseClass. For example
builder = SubClass(context).event_1().event_2() # each call returns a new SubClass, method definitions come from BaseClass
builder.specific_activate()
I've published a minimal working example here https://github.com/jmrgibson/pyo3-subclass-builder-example
My two main questions are:
- is there a better way of doing this?
- would people like me to contribute my working (and any improvements) as an example?
The solution I arrived at was rather more complicated that I initially expected, because of the restrictions around [pyclass] not having any generic arguments, and trying to avoid having the base class having to know about all the extant subclasses.
My solution involves
- the creation of a
Buildertrait - separate builder structs for every different type of pyclass
- each builder struct implements
Builder Box<dyn Builder>s are stored on the base class instance- Type erasure on all the base class methods by using
PyObjectinstead ofBaseClass
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start with the linked pyo3-subclass-builder-example and review the described Builder trait, separate builder structs, boxed dyn Builder values, and PyObject type erasure. Check the [pyclass] restrictions relevant to subclassing and builder return types. Done means reaching a maintainer-approved design and deciding whether an example belongs in PyO3; no repository file or test is named.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python, rust
- Domain
- api, backend-api-design
- Issue type
- Feature
- Difficulty
- 5/5
- Estimated time
- Over a week
- Activity status
- Stale
- Clarity
- Needs clarification
- Newbie friendliness
- 25/100