The decorators in Python are callable objects which in the simplest case is function taking one parameter which is some function or class. The decorator should return again same type which it takes (so if it takes function it should return function). The point is in the time when the decorator is called.
When you import a Python file or just run it directly the Python interpreter goes through the content and gathering information about what classes and function are defined and if it encounter on some code (not declaration) it will execute it.
If the interpreter encounter on decorator it takes the decorated function, call the decorator and replace the decorated function with returned value from the decorator.
Let's say you have this code:
@my_decorator
def my_function()
print("My_function")
It's equivalent to this call:
def my_function()
print("My_function")
my_function = my_decorator(my_function)
If the decorator would be like this one
def my_decorator(func):
print("decorated)
return 42
then the my_function
is not even a function it would be an integer (you can try print(my_function)
)
So when you define decorator as
def my_decorator2(some_fun):
print("before")
some_fun()
print("after")
then this decorator returns nothing (in python it means it returns None
).
@my_decorator2
def decorated():
print("inside")
prints
before
inside
after
but calling decorated()
will raise exception 'NoneType' object is not callable
because the decorated
was replaced with None
.
You should always create decorator which return something useful like function or class (which is usually the "wrap" function inside). Sometimes can be useful to return from decorator something else then function/class but it usually obfuscate your code and convert it into something totally non-maintainable.
just_some_fun()
in your 2nd code block? Yes, stuff gets printed whenmy_decorator
gets called onjust_some_fun
, but when you calljust_some_fun()
it crashes withTypeError: 'NoneType' object is not callable
. – Ecologyprint()
such as amending a string. You will have to return something. – Duly