Decorator Function in Python

Level 4128 keystrokes

This creates a decorator that converts output to uppercase, printing 'HELLO'. Decorators modify function behavior.

Python code

# A decorator is a function that takes a function and returns a new function
1def uppercase(func):
# wrapper is the new function that will replace the original
2 def wrapper():
# Call the original function and convert result to uppercase
3 return func().upper()
# Return the wrapper function
4 return wrapper
5
# @uppercase is syntactic sugar for: greet = uppercase(greet)
6@uppercase
7def greet():
8 return "hello"
9
# Calling greet() actually calls wrapper(), which calls original greet()
10print(greet())

Output

HELLO
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this Python code and how often they appear.

  • (× 7
  • )× 7
  • :× 3
  • "× 2
  • .× 1
  • @× 1

More Python examples at level 4

← Python typing practice