Duško Mirković
Duško Mirković

Reputation: 321

Python decorator with typing package

I'm not sure how to have specific type for decorator's inner function which takes in a function of type Callable[..., Any]. I have the following example written:

from typing import Callable, Any
from threading import Thread, Lock

def synchronized(function: Callable[..., Any]):
    lock = Lock()

    def innerFunction( -- whatAreTheParametersWithTypeHere -- ):
        lock.acquire()
        function( -- whatAreTheParametersWithTypeHere -- )
        lock.release()
    
    return innerFunction

class Test:

    def __init__(self):
        self.__value: int = 0

    @synchronized
    def threadFunc(self):
        self.__value = 0

        for _ in range(10000000):
            self.__value += 1

        print(self.__value)

def main():
    testObj = Test()

    for _ in range(100):
        thread = Thread(target=testObj.threadFunc, args=())
        thread.start()

if __name__ == "__main__":
    main()

Upvotes: 1

Views: 55

Answers (1)

chepner
chepner

Reputation: 531808

Since innerFunction is going to replace the function received as an argument, you can't say anything more than what you already know about function: it's a callable that takes arbitrary arguments and could return anything.

def synchronized(function: Callable[..., Any]):
    lock = Lock()

    def innerFunction(*args, **kwargs):
        lock.acquire()
        function(*args, **kwargs)
        lock.release()
    
    return innerFunction

That said, this isn't a useful decorator. Every decorated function will create and use its own private lock, protecting it from nothing, as no other function can try (and fail) to acquire the lock being held by the decorated function.

Upvotes: 1

Related Questions