[Numpy-discussion] Please help with subclassing numpy.ndarray
Sturla Molden
sturla at molden.no
Tue Feb 6 09:01:37 EST 2007
> Yes using __init__ to set an instance attribute is the Pythonic way to
> do this. However, I calculate/create the data in __new__. The data
> is unavailable to __init__.
The signatures of __new__ and __init__ is:
def __new__(cls, *args, **kwds)
def __init__(self, *args, **kwds)
If __new__ has access to the data, __init__ has access to the data as
well. But in order for __init__ to be called, it must return an instance
of cls. Otherwise, Python leaves the class as returned by __new__.
But it remains that the subclassing example is not thread safe. The only
way to make it thread safe would be if __new__ sets a global lock and
__array_finalize_
releases it. I think NumPy can get away with this because it holds the GIL
inside its C extension, but when you subclass ndarray in Python, the GIL
is released.
More information about the NumPy-Discussion
mailing list