pybind / pybind/pybind11

[QUESTION] Python class as a function parameter

Open
#3,139 0 comments 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

Hi.

I have the following use case, where I would like to create a sort of Python "template" function with types known upfront.

In C++ side, I have a A::create<T>() method that takes a class, creates it underneath and returns a std::shared_ptr to it.
I'd like to have the same behavior in bindings side. Currently what I did was:

.def("create", [](A& a, py::object class_) ...

Where I then use the class_ parameter to check which class to actually create (I have a known set of those bound in advance). The created class is always derived from 1 common class, X. I also expose an API with multiple functions with names indicating the class: createX(), createY(), ...

The issue is that I would rather have an "overload" and that IDEs and stubgen would figure out that passing eg. .create(X) returns an X object and .create(Y) returns a Y object.

I was thinking something the lines of:

.def("create", [](A& a, py::class_<X> x){ return a.create<X>(); }
.def("create", [](A& a, py::class_<Y> y){ return a.create<Y>(); } 

That unfortunately doesn't compile.

How can I suggest to pybind11 that a function takes actual class instead of object as parameter - eg Type[X] instead of X? Option would be also not a exclusively pybind11 solution - maybe something mixed with regular Python code.


As of right now I came up with the following in Python, but not sure if these two things are the same actually:

# test1.py
from __future__ import annotations
from inspect import signature
from typing import overload
from typing import Type

class X(object):
    """Class X"""
        
class Y(object):
    """Class Y"""

@overload
def foo(c: Type[X]) -> X:
    ...
    
@overload
def foo(c: Type[Y]) -> Y:
    ...

def foo(c: Type[X] | Type[Y]) -> X | Y:
    if type(c) == X:
    	return X()
    elif type(c) == Y:
    	return Y()
    else:
    	return X()

reveal_type(foo(X)) # note: Revealed type is "test1.X"
reveal_type(foo(Y)) # note: Revealed type is "test1.Y"

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 proposed .def("create", ...) overloads and the Python overload example in test1.py. Determine whether pybind11 supports class objects as parameters with type-specific return information, and compare that with a regular Python typing solution. Done means identifying a supported approach or documenting why the requested IDE and stubgen behavior is not available.

Written by the indexing model from the issue text.

Assessment

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