writing a class decorator

Viewed 49

i have a class that has a method called my_func(x,s,n). I need to vectorize this function. That is to say, i want to be able to pass x = [3,4,5,6,7] or any range of values and it gives me a result. I am using numpy and looking through here, i managed to find a solution that works. However, I want to make it object oriented. I tried this:

class Vectorize:
    """vectorization wrapper that works with instance methods"""
    def __init__(self, otypes=None, signature=None):
        self.otypes = otypes
        self.sig = signature

    # Decorator as an instance method
    def decorator(self, fn):
        vectorized = np.vectorize(fn, otypes=self.otypes, signature=self.sig)

        @wraps(fn)
        def wrapper(*args, **kwargs):
            return vectorized(*args, **kwargs)
        return wrapper

and then i tried this:

@Vectorize(signature=("(),(),(),()->()"))
def my_func(self, k: int, s: float, n: int):

I keep getting an error, Vectorize object is not callable. Is there any other way to do this? Thanks

1 Answers

I managed to fix this issue. But, now that you have said signature degrades performance, I'm considering alternate solution. For those who are curious:

class Vectorize:
"""vectorization decorator that works with instance methods"""
def vectorize(self, otypes=None, signature=None):
    # Decorator as an instance method
    def decorator(fn):
        vectorized = np.vectorize(fn, otypes=otypes, signature=signature)

        @wraps(fn)
        def wrapper(*args, **kwargs):
            return vectorized(*args, **kwargs)
        return wrapper
    return decorator

class CustomClass:
    v = Vectorize()
    
   @v.vectorize(signature=("(),(),(),()->()"))
   def my_func(self, k: int, s: float, n: int):
Related