PyO3 / PyO3/pyo3

Subclasses and the builder pattern

Open
#3,106 0 comments 0 reactions 0 assignees View on GitHub

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:

  1. is there a better way of doing this?
  2. 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 Builder trait
  • 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 PyObject instead of BaseClass

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. 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

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.