@@ -343,3 +343,75 @@ def hello_goodbye(name):
343343
344344"""Timeout(): a real world example
345345================================="""
346+
347+ ## Tag your functions
348+
349+
350+ def tag (* tags ):
351+ # Define a new decorator, named "decorator", to return
352+ def decorator (func ):
353+ # Ensure the decorated function keeps its metadata
354+ @wraps (func )
355+ def wrapper (* args , ** kwargs ):
356+ # Call the function being decorated and return the result
357+ return func (* args , * kwargs )
358+ wrapper .tags = tags
359+ return wrapper
360+ # Return the new decorator
361+ return decorator
362+
363+ @tag ('test' , 'this is a tag' )
364+ def foo ():
365+ pass
366+
367+ print (foo .tags )
368+
369+ # ('test', 'this is a tag')
370+ #----
371+
372+ ## Check the return type
373+
374+
375+ def returns_dict (func ):
376+ # Complete the returns_dict() decorator
377+ def wrapper (* args , ** kwargs ):
378+ result = func (* args , ** kwargs )
379+ assert (type (result ) == dict )
380+ return result
381+ return wrapper
382+
383+ @returns_dict
384+ def foo (value ):
385+ return value
386+
387+ try :
388+ print (foo ([1 ,2 ,3 ]))
389+ except AssertionError :
390+ print ('foo() did not return a dict!' )
391+
392+ # foo() did not return a dict!
393+
394+ ## Check the return type 2
395+
396+
397+ def returns (return_type ):
398+ # Complete the returns() decorator
399+ def decorator (func ):
400+ def wrapper (* args , ** kwargs ):
401+ result = func (* args , ** kwargs )
402+ assert type (result ) == return_type
403+ return result
404+ return wrapper
405+ return decorator
406+
407+ @returns (dict )
408+ def foo (value ):
409+ return value
410+
411+ try :
412+ print (foo ([1 ,2 ,3 ]))
413+ except AssertionError :
414+ print ('foo() did not return a dict!' )
415+
416+ # <script.py> output:
417+ # foo() did not return a dict!
0 commit comments