avatar Bite 218. Create a sandwich decorator

After creating our Decorators and Context Managers learning path we realized we did not have a beginner decorator Bite, so here it is!

Complete the sandwich decorator which takes a function and prints === Upper bread slice === (defined in UPPER_SLICE) and === Lower bread slice === (defined in LOWER_SLICE) before and after calling the passed in function (func).

And voilà applying this decorator to add_ingredients you have your sandwich (see also the tests):

>>> from sandwich import sandwich
>>> @sandwich
... def add_ingredients(ingredients):
...     print(' / '.join(ingredients))
>>> ingredients = ['bacon', 'lettuce', 'tomato']
>>> add_ingredients(ingredients)
=== Upper bread slice ===
bacon / lettuce / tomato
=== Lower bread slice ===

This is probably the easiest way to demo a decorator. Even so decorators can be confusing when you start using them so here is an article we wrote some time ago: Learning Python Decorators by Example.

Login and get coding
go back Beginner level
Bitecoin 2X

440 out of 449 users completed this Bite.
Will you be Pythonista #441 to crack this Bite?
Resolution time: ~27 min. (avg. submissions of 5-240 min.)
Pythonistas rate this Bite 3.31 on a 1-10 difficulty scale.
» You can do it! 😌

Focus on this Bite hiding sidebars, turn on Focus Mode.

Ask for Help