How Do You Use a Python Function Decorator?

Problem scenario
You want to use a Python function decorator. What do you do?

Background: "A decorator in Python is a function that takes another function as its argument, and returns yet another function." (According to this source.)

Run this program:

def enhanced_multiply(paramfunc):
  def contint(c,d):
    print("I am going to multiply",c,"and",d)
    return paramfunc(c,d)
  return contint # Here is where contint is elegantly & immediately invoked.

def multiply(a,b):
  return a*b

x = multiply(3,8)

Notice the @enhanced_multiply has the "@" syntax. This decorates the function.

Note: If you place a variable assignment or simple print statement between the "@enhanced_multiply" and "def multiply(a,b):", you'll get an error like this:

"SyntaxError: invalid syntax"

We bring this up so you understand how function decorators are invoked; one line with an "@" symbol is directly above a function call. The lower line will not be invoked in an undecorated way in other parts of your program. The "multiply" function is permanently bound to the decorator; to learn more, see this posting.

The decorator in this example enhances the printout of the invocation of the function in the example above. The decorator in this example helps beautify things, but it does not affect the processing of the program. A function decorator is very similar to a function for most purposes.

Leave a comment

Your email address will not be published. Required fields are marked *