I was trying to learn more about Python decorators using excellent tutorial at https://realpython.com/blog/python/primer-on-python-decorators/.
I tried to deviate from the script and am running into some issues. The code is below. Basically, when I run the script below, the first function call to time_print_function() executes as expected.
But I get an error in the next function call my_decorator(print(datetime.datetime.now()))()
I expected that this will produce output same as time_print_function()
Code is
def my_decorator(some_function):
def wrapper(*args):
print "Something is happening before some_function() is called."
if args:
some_function(args)
else:
some_function()
print "Something is happening after some_function() is called."
return wrapper
@my_decorator
def time_print_function():
print(datetime.datetime.now())
time_print_function()
my_decorator(print(datetime.datetime.now()))()
The problem is that this expression:
Already calls the print function before passing it as a parameter to the
my_decorator
call. Themy_decorator
receives the return value ofprint
which is None and tries to call it, yielding an error (None is obviously not callable).The argument to a decorator should be a function - you can create one inline using lambda, for example in: