Get Started

Tag your functions

Tagging something means that you have given that thing one or more strings that act as labels. For instance, we often tag emails or photos so that we can search for them later. You've decided to write a decorator that will let you tag your functions with an arbitrary list of tags. You could use these tags for many things:

  • Adding information about who has worked on the function, so a user can look up who to ask if they run into trouble using it.
  • Labeling functions as "experimental" so that users know that the inputs and outputs might change in the future.
  • Marking any functions that you plan to remove in a future version of the code.
  • Etc.

This is a part of the course

“Writing Functions in Python”

View Course

Exercise instructions

  • Define a new decorator, named decorator(), to return.
  • Ensure the decorated function keeps its metadata.
  • Call the function being decorated and return the result.
  • Return the new decorator.

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

def tag(*tags):
  # Define a new decorator, named "decorator", to return
  def ____(____):
    # Ensure the decorated function keeps its metadata
    @____(____)
    def wrapper(*args, **kwargs):
      # Call the function being decorated and return the result
      return ____(____, ____)
    wrapper.tags = tags
    return wrapper
  # Return the new decorator
  return ____

@tag('test', 'this is a tag')
def foo():
  pass

print(foo.tags)

This exercise is part of the course

Writing Functions in Python

IntermediateSkill Level
4.4+
62 reviews

Learn to use best practices to write maintainable, reusable, complex functions with good documentation.

Now that you understand how decorators work under the hood, this chapter gives you a bunch of real-world examples of when and how you would write decorators in your own code. You will also learn advanced decorator concepts like how to preserve the metadata of your decorated functions and how to write decorators that take arguments.

Exercise 1: Real-world examplesExercise 2: Print the return typeExercise 3: CounterExercise 4: Decorators and metadataExercise 5: Preserving docstrings when decorating functionsExercise 6: Measuring decorator overheadExercise 7: Decorators that take argumentsExercise 8: Run_n_times()Exercise 9: HTML GeneratorExercise 10: Timeout(): a real world exampleExercise 11: Tag your functions
Exercise 12: Check the return typeExercise 13: Great job!

What is DataCamp?

Learn the data skills you need online at your own pace—from non-coding essentials to data science and machine learning.

Start Learning for Free