Python decoder with optional argument of the called argument

Here are many answers on how to determine if a python decorator is used with or without arguments. They usually look like this:

class MyDecorator(object): def __init__(self, *args): if len(args) == 1 and callable(args[0]): # no arguments else: # arguments 

But now I have the following use case:

 @MyDecorator(lambda x:2*x) def foo(): pass 

This is incorrectly defined as a case with no arguments.

Is there any way to detect this situation?

[edit: added missing parameter "self"]

+4
source share
2 answers

Yes, but it will remain a bit hacked. The trick is to use named arguments. In addition, there is no pure way to distinguish between different calls.

 class MyDecorator(object): def __init__(self, *args, **kwargs): if kwargs: # arguments print 'got %r as arguments' else: callable, = args @MyDecorator(some_function=lambda x:2*x) def foo(): pass 
+2
source

The __init__ method requires the self parameter:

 class MyDecorator(object): def __init__(self, *args): if len(args) == 1 and callable(args[0]): # no arguments else: # arguments 

Without this, you always have at least one argument, and it will not be called; instead, it is an instance of the decorator. In other words, without an explicit self , *args will be two elements long when you pass the argument, and it will be the args[1] that you want to test.

+1
source

Source: https://habr.com/ru/post/1497966/


All Articles