|
Size: 1689
Comment: converted to 1.6 markup
|
← Revision 7 as of 2025-10-20 07:34:51 ⇥
Size: 1746
Comment: Fixed minor mistake in the example. Updated syntax to work in Python 3. Replaced bad link with a version in the internet archive.
|
| Deletions are marked like this. | Additions are marked like this. |
| Line 21: | Line 21: |
| return result | return result |
| Line 26: | Line 26: |
| The additional decorate function is needed to work with the Python 2.4 decorator syntax. | The additional decorate function is needed to work with decorator syntax introduced in Python 2.4. |
| Line 32: | Line 32: |
| print "Entering function", func.__name__ | print("Entering function", func.__name__) |
| Line 35: | Line 35: |
| print "Leaving function", func.__name__ | print("Leaving function", func.__name__) |
| Line 45: | Line 45: |
| >>> print calc(1, 2) | >>> print(calc(1, 2)) |
| Line 51: | Line 51: |
| Of course, a wrapper would normally perform some more useful task. Have a look [[http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/412719|here]] for a recipe how to wrap a function that processes files so that the result is recycled from a cache file if appropriate. | Of course, a wrapper would normally perform some more useful task. Have a look [[https://web.archive.org/web/20080609050524/http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/412719|here]] for a recipe how to wrap a function that processes files so that the result is recycled from a cache file if appropriate. |
FunctionWrapper is a design pattern used when dealing with relatively complicated functions. The wrapper function typically performs some prologue and epilogue tasks like
- allocating and disposing resources
- checking pre- and post-conditions
- caching / recycling a result of a slow computation
but otherwise it should be fully compatible with the wrapped function, so it can be used instead of it. (This is related to the DecoratorPattern.)
As of Python 2.1 and the introduction of nested scopes, wrapping a function is easy:
The additional decorate function is needed to work with decorator syntax introduced in Python 2.4.
Now, let's wrap something up:
The wrapping effect is:
Of course, a wrapper would normally perform some more useful task. Have a look here for a recipe how to wrap a function that processes files so that the result is recycled from a cache file if appropriate.
