pybind / pybind/pybind11

proposal: single template to check castability and return result as std::optional

Open
#1,542 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
C++
Stars
18k
Forks
2.3k
Avg merge
5d 17h
Merged PRs (30d)
10

Description

Issue description

I find myself often checking whether a particular py::object wraps this or that c++ class, and if it does, extract the result. This can be done with explicit try-catch block, like

py::object obj;
shared_ptr<T> i;
try { i=std::cast<shared_ptr<T>>(obj); } except(...) { };
if(i) // use i;    

or yet worse, with the conversion done twice:

bool ok=true;
try { std::cast<shared_ptr<T>>(obj); } except(...) { ok=false };
if(ok){
   std::cast<shared_ptr<T>> i=(obj);
   /* .... */
}

What I propose is to have a template class encompassing this dual functionality (check whether the conversion is possible, return the result if it is). boost::python did something similar with extract::check() and extract::operator() but with c++17, it would be natural to use std::optional for this.

py::object obj;
py::optional_cast<T> i(obj);
if(i){ /* use i.value() */ };

or yet more compact

if(auto i=py::optional_cast<T>(obj)){ /* use i.value() */ }

Would this fit pybind11's design?

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

Review the existing py::object casting interface and the proposed optional_cast usage, including the try-catch and std::optional examples in the issue. Determine whether a single castability-and-result API fits pybind11's design and what behavior would define a complete proposal.

Written by the indexing model from the issue text.

Assessment

Tech stack
cpp, python
Domain
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.