Search code examples
pythonpytestcythonsubclass

Is there a way to trick isinstance results for a class?


(Edited the title because the answer applies to any class, not just cython classes)

I am developing my extended types with a very tight restriction on performance, and I'm happy with the results.

I've found that for a type that is basically a float restricted to 0 < value < 360 it's faster to not base on float, but to store the value as an attribute and reproduce whichever methods from float are needed.

The one problem I've found with this is that tests using pytest.approx do not work except for trivial exact values, as ApproxScalar only attempts to make further comparisons if the type is a subclass of Complex or Decimal.

Is there any way within python/cython by which I can trick an isinstance call to believe than my class is a float instance?


Solution

  • numbers.Complex is an abstract base class so has a register method that you can use to associate any Python type with it so that it returns True for isinstance.

    The fact the class you want to register is a Cython cdef class doesn't matter at all