79648081

Date: 2025-06-02 01:19:12
Score: 1
Natty:
Report link

While I generally agree with @jsbueno 's answer that overloading will require `typing.overload` I'm not sure it is needed for your example.

Sure, regarding the part of your question about "Can I somehow 'overload' decorator?" yes, you can and you would need `typing.overload` (as already mentioned) and you can read more about it in the official PEP-484 (python-enhancement-proposal) specifically the part about overloading: https://peps.python.org/pep-0484/#function-method-overloading

However, decorators are going to behave more like a C++ generic constructor for functions in your example through some syntactic sugar. So, regarding the remaining part of your question: "Can I use some nice solutions in this case?" yes, just make the method static.

The only issue with your example code I see is the class method is not marked as 'static' but implemented as static, yet called on the instance when used.

e.g, more decorators is simple and works in this case

   # double decorate static class method to drop the unused self argument
   @nice
   @staticmethod
   def sumup(a, b):
       return a + b

This way your @nice decorator takes the "static" "member" method (e.g., instead of the C++ covariant-like argument) output by the @staticmethod decorator which takes the static class function as input, you could also move the scope of a, b, to the decorator like so:

def nice(f, *args, **kwargs):
   @wraps(f)
   def decorator(*args, **kwargs):
       result = f(*args, **kwargs)
       return 'result is: %s' % str(result)
   
   return decorator

from my light testing:

from functools import wraps
def nice(f, *args, **kwargs):
    @wraps(f)
    def decorator(*args, **kwargs):
        result = f(*args, **kwargs)
        return 'result is: %s' % str(result)
    
    return decorator


@nice
def sumup(a, b):
    return a+ b


# >>> sumup(9, 8)
# 'result is: 17'
# >>> 

# >>> class Test:
# ...    def __init__(self):
# ...        pass
# ...    
# ...    @nice
# ...    def sumup(self, a, b):
# ...        return a + b
# ...        
# >>> cls = Test()
# ... print(cls.sumup(4, 8))
# ... 
# result is: 12
# >>> 

sorry for the rushed answer, hopefully this helps.

Reasons:
  • Long answer (-1):
  • Has code block (-0.5):
  • Contains question mark (0.5):
  • User mentioned (1): @jsbueno
  • Low reputation (1):
Posted by: Reactive-Firewall