Using python decorator with or without parentheses

后端 未结 4 1778
心在旅途
心在旅途 2021-02-01 01:04

In Python, what is the difference between using the same decorator with and without parentheses?

For example:

Without parentheses:

@some         


        
4条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-02-01 01:37

    Some actually working code where you use the arg inside decorator:

    def someDecorator(arg=None):
        def decorator(func):
            def wrapper(*a, **ka):
                if not callable(arg):
                    print (arg)
                    return func(*a, **ka)
                else:
                    return 'xxxxx'
            return wrapper
    
        if callable(arg):
            return decorator(arg) # return 'wrapper'
        else:
            return decorator # ... or 'decorator'
    
    @someDecorator(arg=1)
    def my_func():
        print('aaa')
    
    @someDecorator
    def my_func1():
        print('bbb')
    
    if __name__ == "__main__":
        my_func()
        my_func1()
    

    The output is:

    1
    aaa
    

提交回复
热议问题