Skip to content

Cannot register a class with an abstract method. #1359

@Fung-Chai

Description

@Fung-Chai

Hi,

I am trying to register a class that has an abstract method. The idea is for clients to define the method in their subclasses. However, the registration fails.

Before I forget, I am running on Ubuntu 16.04, using pybind11 version 2.2.2, python 2.7.12, g++ version 5.4.0, and -std=c++11.

Here is what I am trying to do:

py::module abc = py::module::import("abc");
py::object abc_meta = abc.attr("ABCMeta");
py::object abstract = abc.attr("abstractmethod");

py::module mod{"example"};
py::class_<Base> base(mod, "Base", py::metaclass(abc_meta));
base.def("draw", &Base::draw, "Abstract method that subclasses must define");
base.attr("draw") = abstract(base.attr("draw"));
base.def("save", &Base::save, "Save into file");

Here, I have a class that offers the save() function. But I require clients to create a subclass and define the draw() function.

When I compile and run the code, I get the following error:

terminate called after throwing an instance of 'pybind11::error_already_set'
  what():  AttributeError: type object 'example.Base' has no attribute '_abc_cache'

At:
  /usr/lib/python2.7/abc.py(151): __subclasscheck__

Since ABCMeta is trying to add _abc_cache and other attributes to my base class, I thought adding dynamic_attr() might help. I get the same error message with the following:

py::class_<Base> base(mod, "Base", py::metaclass(abc_meta), py::dynamic_attr());

I would appreciate any help on this. Thank you.

In the attached file, I am embedding the python interpreter so that I do not need a python script to import my example module.
main.cpp.txt

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions