Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use a more uniform structure for cython classes #1289

Open
arcondello opened this issue Nov 10, 2022 · 1 comment
Open

Use a more uniform structure for cython classes #1289

arcondello opened this issue Nov 10, 2022 · 1 comment
Labels
feature-request/enhancement New feature or request

Comments

@arcondello
Copy link
Member

arcondello commented Nov 10, 2022

Currently we have two patterns for Cython classes and it would be nice to be more consistent

Subclass pattern

Have a Cython class as a superclass of the Python class

cdef class cyClass:
    ...

class Class(cyClass):
    ...

examples: cyVariables and Variables, cyConstrainedQuadraticModel and ConstrainedQuadraticModel

The major drawback of this pattern is it does not allow multiple data types, because Cython does not allow templated classes (nor is such a concept really meaningful).

Attribute pattern

Have the Python class hold the Cython class as an attribute

cdef class cyClass
    ...

class Class:
    def __init__(self):
        self.data = cyClass()

examples: cyBQM and BQM

This pattern gives us the ability to support multiple underlying data types, but IMO it's harder to understand and requires a lot of indirect methods like

def f(self):
    return self.data.f()

which adds clutter and maintenance and creates a performance problem (partially mititgated by forwarding_method).

@arcondello arcondello added the feature-request/enhancement New feature or request label Nov 10, 2022
@arcondello
Copy link
Member Author

arcondello commented Nov 10, 2022

One potential alternative to the attribute pattern would be something like

import abc

import numpy as np

class BQM_float64:
    pass


class BQM_float32:
    pass


class BQM(abc.ABC):
    def __new__(cls, *args, dtype=np.float64, **kwargs):
        if dtype == np.float32:
            return BQM_float32(*args, **kwargs)
        elif dtype == np.float64:
            return BQM_float64(*args, **kwargs)
        else:
            raise ValueError

BQM.register(BQM_float64)
BQM.register(BQM_float32)

where we create a stub BQM class that just constructs one of the two other datatype classes. Which themselves can inherit from the Cython classes.

That said, this has some issues. Namely it's a bit surprising for a user, and the docs etc will break.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
feature-request/enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

1 participant