Get startedGet started for free

Check the return type

Python's flexibility around data types is usually cited as one of the benefits of the language. It can sometimes cause problems though if incorrect data types go unnoticed. You've decided that in order to ensure your code is doing exactly what you want it to do, you will explicitly check the return types in all of your functions and make sure they're returning what you expect. To do that, you are going to create a decorator that checks if the return type of the decorated function is correct.

Note: assert is a keyword that you can use to test whether something is true. If you type assert condition and condition is True, this function doesn't do anything. If condition is False, this function raises an error. The type of error that it raises is called an AssertionError.

This exercise is part of the course

Writing Functions in Python

View Course

Hands-on interactive exercise

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

def returns_dict(func):
  # Complete the returns_dict() decorator
  def wrapper(____):
    result = ____
    assert type(result) == dict
    return result
  ____
  
@returns_dict
def foo(value):
  return value

try:
  print(foo([1,2,3]))
except AssertionError:
  print('foo() did not return a dict!')
  
Edit and Run Code