@@ -91,9 +91,12 @@ def foo():
9191# foo() was called 2 times.
9292
9393"""Decorators and metadata
94- ==========================="""
94+ ===========================
95+ >>>>>>>> from functools import wraps ==== add the metadata from wrapper to the decorated version of print_sum().
96+ >>>>>>>> @wraps ==== Decorate wrapper() so that it keeps func()'s metadata"""
9597## Preserving docstrings when decorating functions
9698
99+
97100def add_hello (func ):
98101 def wrapper (* args , ** kwargs ):
99102 print ('Hello' )
@@ -116,6 +119,7 @@ def print_sum(a, b):
116119
117120## Preserving docstrings when decorating functions 2
118121
122+
119123# you're printing wrapper docstring , not add hello docstring"""
120124def add_hello (func ):
121125 # Add a docstring to wrapper
@@ -141,3 +145,50 @@ def print_sum(a, b):
141145
142146## Preserving docstrings when decorating functions 3
143147
148+
149+ # Import the function you need to fix the problem
150+ # will allow you to add the metadata from print_sum() to the decorated version of print_sum().
151+ from functools import wraps
152+
153+ def add_hello (func ):
154+ def wrapper (* args , ** kwargs ):
155+ """Print 'hello' and then call the decorated function."""
156+ print ('Hello' )
157+ return func (* args , ** kwargs )
158+ return wrapper
159+
160+ @add_hello
161+ def print_sum (a , b ):
162+ """Adds two numbers and prints the sum"""
163+ print (a + b )
164+
165+ print_sum (10 , 20 )
166+ print_sum_docstring = print_sum .__doc__
167+ print (print_sum_docstring )
168+
169+ ## Preserving docstrings when decorating functions 4
170+
171+
172+ from functools import wraps
173+
174+ def add_hello (func ):
175+ # Decorate wrapper() so that it keeps func()'s metadata
176+ @wraps (func )
177+ def wrapper (* args , ** kwargs ):
178+ """Print 'hello' and then call the decorated function."""
179+ print ('Hello' )
180+ return func (* args , ** kwargs )
181+ return wrapper
182+
183+ @add_hello
184+ def print_sum (a , b ):
185+ """Adds two numbers and prints the sum"""
186+ print (a + b )
187+
188+ print_sum (10 , 20 )
189+ print_sum_docstring = print_sum .__doc__
190+ print (print_sum_docstring )
191+
192+ # Hello
193+ # 30
194+ # Adds two numbers and prints the sum
0 commit comments