pybind / pybind/pybind11

Abstract classes and methods are not abstract after wrapping

Open
#1,978 6 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

Issue description

In C++, abstract classes are defined as classes that contain pure virtual methods. Python's equivalent has been introduced in PEP -3119 – Abstract Base Classes.
Both cases represent the same concept: Types that cannot be instantiated and merely define a generic interface.

pybind11 already knows the notion of pure virtual functions and provides PYBIND11_OVERLOAD_PURE. In order to be compatible with python, classes containing such methods should be registered as Abstract Base Classes, the respective methods should be decorated with @abstractmethod.

Reproducible example code

C++
#include <pybind11/pybind11.h>

namespace py = pybind11;

class Abstract {
public:
	virtual ~Abstract() = default;

	virtual void some_method() = 0;
};


class PyAbstract : public Abstract {
public:
	using Abstract::Abstract;

	void some_method() override {
		PYBIND11_OVERLOAD_PURE(void, Abstract, some_method)
	}
};

PYBIND11_MODULE(abc_example, m) {
	py::class_<Abstract, PyAbstract>(m, "Abstract")
			.def(py::init<>())
			.def("some_method", &Abstract::some_method);
}
Python test
import unittest
import inspect
from abc_example import Abstract

class AbstractBaseTest(unittest.TestCase):
    def test_is_abstract(self):
        self.assertTrue(inspect.isabstract(Abstract))

    def test_abstract_method(self):
        self.assertTrue(
            getattr(Abstract.some_method, "__isabstractmethod__", False)
        )

if __name__ == '__main__':
    unittest.main()

With the most recent version of pybind11 (tested: 2.4.3), both tests fail.

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 py::class_ registration and PYBIND11_OVERLOAD_PURE usage shown in the C++ example, then compare them with Python's abc and inspect.isabstract behavior. Use the provided AbstractBaseTest checks as the acceptance criteria: the wrapped class must be recognized as abstract and its bound method must expose isabstractmethod.

Written by the indexing model from the issue text.

Assessment

Tech stack
cpp, python
Domain
backend-api-design
Issue type
Feature
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.