From 7b391ceaf4d46bd2fe1464379fc48d6b3c8b6b01 Mon Sep 17 00:00:00 2001 From: "michele.simionato" Date: Wed, 3 Dec 2008 06:58:37 +0000 Subject: Started the work on version 3.0 of the decorator module --- CHANGES.txt | 52 ++++ Makefile | 15 + README.txt | 22 ++ corner-cases.txt | 40 +++ decorator.py | 129 ++++++++ documentation.py | 923 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ other.txt | 125 ++++++++ performance.sh | 16 + setup.py | 37 +++ util.py | 14 + 10 files changed, 1373 insertions(+) create mode 100755 CHANGES.txt create mode 100755 Makefile create mode 100755 README.txt create mode 100755 corner-cases.txt create mode 100755 decorator.py create mode 100644 documentation.py create mode 100755 other.txt create mode 100644 performance.sh create mode 100644 setup.py create mode 100755 util.py diff --git a/CHANGES.txt b/CHANGES.txt new file mode 100755 index 0000000..5b77483 --- /dev/null +++ b/CHANGES.txt @@ -0,0 +1,52 @@ +HISTORY +---------- + +2.3.2. Small optimization in the code for decorator factories. First version + with the code uploaded to PyPI (01/12/2008) +2.3.1. Set the zipsafe flag to False, since I want my users to have the source, not + a zipped egg (25/07/2008) +2.3.0. Added support for writing decorator factories with minimal effort (feature + requested by Matthew Wilson); implemented it by enhancing 'decorator' to + a Python 2.6 class decorator (10/07/2008) +2.2.0. Added a note on 'inspect.getsource' not working for decorated + functions; referenced PEP 326; highlighted the snippets in the + documentation with pygments; slightly simplified the code (31/07/2007) +2.1.0. Replaced the utility 'update_wrapper' with 'new_wrapper' and + updated the documentation accordingly; fixed and improved the + doctester argument parsing, signaled by Sam Wyse (3/07/2007) +2.0.1. Included the licence in the source code too; fixed a versioning + issue by adding the version number to the zip file and fixing + the link to it on the web page, thanks to Philip Jenvey (17/02/2007) +2.0. Rewritten and simplified the implementation; broken compatibility + with previous versions (in minor ways); added the utility function + 'update_wrapper' instead of 'newfunc' (13/01/2007) +1.1. 'decorator' instances now have attributes __name__, __doc__, + __module__ and __dict__ coming from the associated caller function; + included the licence into the documentation (02/12/2006) +1.0. Added LICENCE.txt; added a setuptools-friendly setup.py script + contributed by Luke Arno (10/08/2006) +0.8.1. Minor fixes to the documentation (21/06/2006) +0.8. Improved the documentation, added the 'caveats' section (16/06/2006) +0.7.1. Improved the tail_recursive example (15/05/2006) +0.7. Renamed 'copyfunc' into 'newfunc' and added the ability to copy + the signature from a model function; improved '_decorator' to + set the '__module__' attribute too, with the intent of improving + error messages; updated the documentation (10/05/2006) +0.6. Changed decorator.__call__ so that the module somewhat works + even for Python 2.3 (but the signature-preserving feature is + lost) (20/12/2005) +0.5.2. Minor changes to the documentation; improved 'getattr_' and + shortened 'locked' (28/06/2005) +0.5.1. Minor corrections to the documentation (20/05/2005) +0.5. Fixed a bug with out-of-the-mind signatures, added a check for reserved + names in the argument list and simplified the code (thanks to Duncan + Booth) (19/05/2005) +0.4.1. Fixed a typo in the documentation (thanks to Anthon van der Neut) + (17/05/2005) +0.4. Added getinfo, some tests and improved the documentation (12/05/2005) +0.3. Simplified copyfunc, renamed deferred to delayed and added the + nonblocking example (10/05/2005) +0.2. Added copyfunc, improved the multithreading examples, improved + the doctester program (09/05/2005) +0.1.1. Added the license specification and two docstrings (06/05/2005) +0.1. Initial release (04/05/2005) diff --git a/Makefile b/Makefile new file mode 100755 index 0000000..738bc81 --- /dev/null +++ b/Makefile @@ -0,0 +1,15 @@ +T = /home/micheles/trunk/ROnline/RCommon/Python/ms/tools +V = 2.3.2 + +documentation.html: documentation.txt + python $T/rst.py documentation +documentation.pdf: documentation.txt + python $T/rst.py -tp documentation +pdf: documentation.pdf + evince documentation.pdf& +decorator-$V.zip: README.txt documentation.txt documentation.html documentation.pdf \ +doctester.py decorator.py setup.py CHANGES.txt performance.sh + zip decorator-$V.zip README.txt documentation.txt documentation.html \ +documentation.pdf decorator.py setup.py doctester.py CHANGES.txt performance.sh +upload: decorator-$V.zip + scp decorator-$V.zip documentation.html alpha.phyast.pitt.edu:public_html/python diff --git a/README.txt b/README.txt new file mode 100755 index 0000000..859f89c --- /dev/null +++ b/README.txt @@ -0,0 +1,22 @@ +Decorator module +--------------------------- + +Dependencies: + +The decorator module requires Python 2.4. + +Installation: + +Unzip the archive in a directory called "decorator" in your Python path. +For instance, on Unices you could give something like that: + +$ unzip decorator.zip -d decorator + +Testing: + +Just go in the package directory and give + +$ python doctester.py documentation.txt + +This will generate the main.py file containing all the examples +discussed in the documentation, and will run the corresponding tests. diff --git a/corner-cases.txt b/corner-cases.txt new file mode 100755 index 0000000..510addc --- /dev/null +++ b/corner-cases.txt @@ -0,0 +1,40 @@ +>>> from decorator import decorator +>>> @decorator +... def identity_dec(f, *a, **k): return f(*a, **k) +... +>>> #defarg=1 +>>> @identity_dec +... def f(f=1): print f +... +>>> f() +1 + +>>> @identity_dec +... def f(_call_): print f +... +Traceback (most recent call last): + ... +AssertionError: You cannot use _call_ or _func_ as argument names! + +>>> @identity_dec +... def f(**_func_): print f +... +Traceback (most recent call last): + ... +AssertionError: You cannot use _call_ or _func_ as argument names! + +>>> @identity_dec +... def f(name): print name +... + +>>> f("z") +z + +The decorator module also works for exotic signatures: + +>>> @identity_dec +... def f((a, (x, (y, z), w)), b): +... print a, b, x, y, z, w + +>>> f([1, [2, [3, 4], 5]], 6) +1 6 2 3 4 5 diff --git a/decorator.py b/decorator.py new file mode 100755 index 0000000..e9a35e0 --- /dev/null +++ b/decorator.py @@ -0,0 +1,129 @@ +########################## LICENCE ############################### + +## Redistributions of source code must retain the above copyright +## notice, this list of conditions and the following disclaimer. +## Redistributions in bytecode form must reproduce the above copyright +## notice, this list of conditions and the following disclaimer in +## the documentation and/or other materials provided with the +## distribution. + +## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +## "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +## LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +## A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +## HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +## INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +## BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS +## OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +## ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR +## TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE +## USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH +## DAMAGE. + +""" +Decorator module, see http://pypi.python.org/pypi/decorator +for the documentation. +""" + +## The basic trick is to generate the source code for the decorated function +## with the right signature and to evaluate it. + +__all__ = ["decorator", "makefn", "getsignature", "upgrade_dec"] + +import os, sys, re, inspect, warnings +from tempfile import mkstemp + +DEF = re.compile('\s*def\s*([_\w][_\w\d]*)\s*\(') + +def _callermodule(level=2): + return sys._getframe(level).f_globals.get('__name__', '?') + +def getsignature(func): + "Return the signature of a function as a string" + argspec = inspect.getargspec(func) + return inspect.formatargspec(formatvalue=lambda val: "", *argspec)[1:-1] + +class FuncData(object): + def __init__(self, func=None, name=None, signature=None, + defaults=None, doc=None, module=None, funcdict=None): + if func: # func can also be a class or a callable + self.name = func.__name__ + self.doc = func.__doc__ + self.module = func.__module__ + if inspect.isfunction(func): + self.signature = getsignature(func) + self.defaults = func.func_defaults + self.dict = func.__dict__ + if name: + self.name = name + if signature: + self.signature = signature + if defaults: + self.defaults = defaults + if doc: + self.doc = doc + if module: + self.module = module + if funcdict: + self.dict = funcdict + + def update(self, func, **kw): + func.__name__ = getattr(self, 'name', 'noname') + func.__doc__ = getattr(self, 'doc', None) + func.__dict__ = getattr(self, 'dict', {}) + func.func_defaults = getattr(self, 'defaults', None) + func.__module__ = getattr(self, 'module', _callermodule()) + func.__dict__.update(kw) + return func + + def __getitem__(self, name): + return getattr(self, name) + +def makefn(src, funcdata, save_source=True, **evaldict): + src += os.linesep # add a newline just for safety + name = DEF.match(src).group(1) # extract the function name from the source + if save_source: + fhandle, fname = mkstemp() + os.write(fhandle, src) + os.close(fhandle) + else: + fname = '?' + code = compile(src, fname, 'single') + exec code in evaldict + func = evaldict[name] + return funcdata.update(func, __source__=src) + +def decorator(caller, func=None): + """ + decorator(caller) converts a caller function into a decorator; + decorator(caller, func) is akin to decorator(caller)(func). + """ + if func: + fd = FuncData(func) + name = fd.name + signature = fd.signature + for arg in signature.split(','): + argname = arg.strip(' *') + assert not argname in('_func_', '_call_'), ( + '%s is a reserved argument name!' % argname) + src = """def %(name)s(%(signature)s): + return _call_(_func_, %(signature)s)""" % locals() + return makefn(src, fd, save_source=False, _func_=func, _call_=caller) + src = 'def %s(func): return decorator(caller, func)' % caller.__name__ + return makefn(src, FuncData(caller), save_source=False, + caller=caller, decorator=decorator) + +@decorator +def deprecated(func, *args, **kw): + "A decorator for deprecated functions" + warnings.warn('Calling the deprecated function %r' % func.__name__, + DeprecationWarning, stacklevel=3) + return func(*args, **kw) + +def upgrade_dec(dec): + def new_dec(func): + fd = FuncData(func) + src = '''def %(name)s(%(signature)s): + return decorated(%(signature)s)''' % fd + return makefn(src, fd, save_source=False, decorated=dec(func)) + return FuncData(dec).update(new_dec) diff --git a/documentation.py b/documentation.py new file mode 100644 index 0000000..3d5f88a --- /dev/null +++ b/documentation.py @@ -0,0 +1,923 @@ +"""\ +The ``decorator`` module +============================================================= + +:author: Michele Simionato +:E-mail: michele.simionato@gmail.com +:version: 3.0 (11 December 2008) +:Download page: http://pypi.python.org/decorator +:Installation: ``easy_install decorator`` +:License: BSD license + +.. contents:: + +Introduction +------------------------------------------------ + +Python 2.4 decorators are an interesting example of why syntactic sugar +matters: in principle, their introduction changed nothing, since they do +not provide any new functionality which was not already present in the +language; in practice, their introduction has significantly changed the way +we structure our programs in Python. I believe the change is for the best, +and that decorators are a great idea since: + +* decorators help reducing boilerplate code; +* decorators help separation of concerns; +* decorators enhance readability and maintenability; +* decorators are very explicit. + +Still, as of now, writing custom decorators correctly requires +some experience and it is not as easy as it could be. For instance, +typical implementations of decorators involve nested functions, and +we all know that flat is better than nested. + +The aim of the ``decorator`` module it to simplify the usage of +decorators for the average programmer, and to popularize decorators +usage giving examples of useful decorators, such as ``memoize``, +``tracing``, ``redirecting_stdout``, ``locked``, etc. + +The core of this module is a decorator factory called ``decorator``. +All decorators discussed here are built as simple recipes on top +of ``decorator``. You may find their source code in the ``documentation.py`` +file. If you execute it, all the examples contained will be doctested. + +Definitions +------------------------------------ + +Technically speaking, any Python object which can be called with one argument +can be used as a decorator. However, this definition is somewhat too large +to be really useful. It is more convenient to split the generic class of +decorators in two groups: + ++ *signature-preserving* decorators, i.e. callable objects taking a + function as input and returning a function *with the same + signature* as output; + ++ *signature-changing* decorators, i.e. decorators that change + the signature of their input function, or decorators returning + non-callable objects. + +Signature-changing decorators have their use: for instance the +builtin classes ``staticmethod`` and ``classmethod`` are in this +group, since they take functions and return descriptor objects which +are not functions, nor callables. + +However, signature-preserving decorators are more common and easier to +reason about; in particular signature-preserving decorators can be +composed together whereas other +decorators in general cannot (for instance you cannot +meaningfully compose a staticmethod with a classmethod or viceversa). + +Writing signature-preserving decorators from scratch is not that +obvious, especially if one wants to define proper decorators that +can accept functions with any signature. A simple example will clarify +the issue. + +Statement of the problem +------------------------------ + +Suppose you want to trace a function: this is a typical use case +for a decorator and you can find in many places code like this: + +.. code-block:: python + + try: + from functools import update_wrapper + except ImportError: # using Python version < 2.5 + def decorator_trace(f): + def newf(*args, **kw): + print "calling %s with args %s, %s" % (f.__name__, args, kw) + return f(*args, **kw) + newf.__name__ = f.__name__ + newf.__dict__.update(f.__dict__) + newf.__doc__ = f.__doc__ + newf.__module__ = f.__module__ + return newf + else: # using Python 2.5+ + def decorator_trace(f): + def newf(*args, **kw): + print "calling %s with args %s, %s" % (f.__name__, args, kw) + return f(*args, **kw) + return update_wrapper(newf, f) + +The implementation above works in the sense that the decorator +can accept functions with generic signatures; unfortunately this +implementation does *not* define a signature-preserving decorator, since in +general ``decorator_trace`` returns a function with a +*different signature* from the original function. + +Consider for instance the following case: + +>>> @decorator_trace +... def f1(x): +... pass + +Here the original function takes a single argument named ``x``, +but the decorated function takes any number of arguments and +keyword arguments: + +>>> from inspect import getargspec +>>> print getargspec(f1) +([], 'args', 'kw', None) + +This means that introspection tools such as pydoc will give +wrong informations about the signature of ``f1``. This is pretty bad: +pydoc will tell you that the function accepts a generic signature +``*args``, ``**kw``, but when you try to call the function with more than an +argument, you will get an error: + +>>> f1(0, 1) +Traceback (most recent call last): + ... +TypeError: f1() takes exactly 1 argument (2 given) + +The solution +----------------------------------------- + +The solution is to provide a generic factory of generators, which +hides the complexity of making signature-preserving decorators +from the application programmer. The ``decorator`` factory +allows to define decorators without the need to use nested functions +or classes. As an example, here is how you can define +``decorator_trace``. + +First of all, you must import ``decorator``: + +>>> from decorator import decorator + +Then you must define an helper function with signature ``(f, *args, **kw)`` +which calls the original function ``f`` with arguments ``args`` and ``kw`` +and implements the tracing capability: + +$$_trace + +$$trace + +Therefore, you can write the following: + +>>> @trace +... def f1(x): +... pass + +It is immediate to verify that ``f1`` works + +>>> f1(0) +calling f1 with args (0,), {} + +and it that it has the correct signature: + +>>> print getargspec(f1) +(['x'], None, None, None) + +The same decorator works with functions of any signature: + +>>> @trace +... def f(x, y=1, z=2, *args, **kw): +... pass + +>>> f(0, 3) +calling f with args (0, 3, 2), {} + +>>> print getargspec(f) +(['x', 'y', 'z'], 'args', 'kw', (1, 2)) + +That includes even functions with exotic signatures like the following: + +>>> @decorator(trace) +... def exotic_signature((x, y)=(1,2)): return x+y + +>>> print getargspec(exotic_signature) +([['x', 'y']], None, None, ((1, 2),)) +>>> exotic_signature() +calling exotic_signature with args ((1, 2),), {} +3 + +Notice that exotic signatures have been disabled in Python 3.0. + +``decorator`` is a decorator +--------------------------------------------- + +``decorator`` is able to convert the helper function into a +signature-preserving decorator +object, i.e is a callable object that takes a function and returns a +decorated function with the same signature of the original function. + +The ``decorator`` factory itself can be considered as a signature-changing +decorator, just as ``classmethod`` and ``staticmethod``. +However, ``classmethod`` and ``staticmethod`` return generic +objects which are not callable, while ``decorator`` returns +signature-preserving decorators, i.e. functions of a single argument. +Therefore, you can write + +>>> @decorator +... def tracing(f, *args, **kw): +... print "calling %s with args %s, %s" % (f.func_name, args, kw) +... return f(*args, **kw) + +and this idiom is actually redefining ``tracing`` to be a decorator. +We can easily check that the signature has changed: + +>>> print getargspec(tracing) +(['func'], None, None, None) + +Therefore now ``tracing`` can be used as a decorator and +the following will work: + +>>> @tracing +... def func(): pass + +>>> func() +calling func with args (), {} + +BTW, you may use the decorator on lambda functions too: + +>>> tracing(lambda : None)() +calling with args (), {} + +For the rest of this document, I will discuss examples of useful +decorators built on top of ``decorator``. + +``memoize`` +--------------------------------------------------------- + +This decorator implements the ``memoize`` pattern, i.e. it caches +the result of a function in a dictionary, so that the next time +the function is called with the same input parameters the result is retrieved +from the cache and not recomputed. There are many implementations of +``memoize`` in http://www.python.org/moin/PythonDecoratorLibrary, +but they do not preserve the signature. + +$$_memoize + +$$memoize + +Here is a test of usage: + +>>> @memoize +... def heavy_computation(): +... time.sleep(2) +... return "done" + +>>> print heavy_computation() # the first time it will take 2 seconds +done + +>>> print heavy_computation() # the second time it will be instantaneous +done + +As an exercise, try to implement ``memoize`` *properly* without the +``decorator`` factory. + +For sake of semplicity, my implementation only works for functions +with no keyword arguments. One can relax this requirement, and allow +keyword arguments in the signature, for instance by using ``(args, +tuple(kwargs.iteritems()))`` as key for the memoize dictionary. +Notice that in general it is impossible to memoize correctly something +that depends on mutable arguments. + +``locked`` +--------------------------------------------------------------- + +There are good use cases for decorators is in multithreaded programming. +For instance, a ``locked`` decorator can remove the boilerplate +for acquiring/releasing locks [#]_. + +.. [#] In Python 2.5, the preferred way to manage locking is via + the ``with`` statement: http://docs.python.org/lib/with-locks.html + +To show an example of usage, suppose one wants to write some data to +an external resource which can be accessed by a single user at once +(for instance a printer). Then the access to the writing function must +be locked: + +.. code-block:: python + + import time + + datalist = [] # for simplicity the written data are stored into a list. + + @locked + def write(data): + "Writing to a sigle-access resource" + time.sleep(1) + datalist.append(data) + + +Since the writing function is locked, we are guaranteed that at any given time +there is at most one writer. An example multithreaded program that invokes +``write`` and prints the datalist is shown in the next section. + +``delayed`` and ``threaded`` +-------------------------------------------- + +Often, one wants to define families of decorators, i.e. decorators depending +on one or more parameters. + +Here I will consider the example of a one-parameter family of ``delayed`` +decorators taking a procedure and converting it into a delayed procedure. +In this case the time delay is the parameter. + +A delayed procedure is a procedure that, when called, +is executed in a separate thread after a certain time +delay. The implementation is not difficult: + +$$delayed + +Notice that without the help of ``decorator``, an additional level of +nesting would have been needed. + +Delayed decorators as intended to be used on procedures, i.e. +on functions returning ``None``, since the return value of the original +function is discarded by this implementation. The decorated function returns +the current execution thread, which can be stored and checked later, for +instance to verify that the thread ``.isAlive()``. + +Delayed procedures can be useful in many situations. For instance, I have used +this pattern to start a web browser *after* the web server started, +in code such as + +>>> @delayed(2) +... def start_browser(): +... "code to open an external browser window here" + +>>> #start_browser() # will open the browser in 2 seconds +>>> #server.serve_forever() # enter the server mainloop + +The particular case in which there is no delay is important enough +to deserve a name: + +.. code-block:: python + + threaded = delayed(0) + +Threaded procedures will be executed in a separated thread as soon +as they are called. Here is an example using the ``write`` +routine defined before: + +>>> @threaded +... def writedata(data): +... write(data) + +Each call to ``writedata`` will create a new writer thread, but there will +be no synchronization problems since ``write`` is locked. + +>>> writedata("data1") +<_Timer(Thread-1, started)> + +>>> time.sleep(.1) # wait a bit, so we are sure data2 is written after data1 + +>>> writedata("data2") +<_Timer(Thread-2, started)> + +>>> time.sleep(2) # wait for the writers to complete + +>>> print datalist +['data1', 'data2'] + +``blocking`` +------------------------------------------- + +Sometimes one has to deal with blocking resources, such as ``stdin``, and +sometimes it is best to have back a "busy" message than to block everything. +This behavior can be implemented with a suitable decorator: + +$$blocking + +Functions decorated with ``blocking`` will return a busy message if +the resource is unavailable, and the intended result if the resource is +available. For instance: + +>>> @blocking("Please wait ...") +... def read_data(): +... time.sleep(3) # simulate a blocking resource +... return "some data" + +>>> print read_data() # data is not available yet +Please wait ... + +>>> time.sleep(1) +>>> print read_data() # data is not available yet +Please wait ... + +>>> time.sleep(1) +>>> print read_data() # data is not available yet +Please wait ... + +>>> time.sleep(1.1) # after 3.1 seconds, data is available +>>> print read_data() +some data + +``redirecting_stdout`` +------------------------------------------- + +Decorators help in removing the boilerplate associated to ``try .. finally`` +blocks. We saw the case of ``locked``; here is another example: + +$$redirecting_stdout + +Here is an example of usage: + +>>> from StringIO import StringIO + +>>> out = StringIO() + +>>> @redirecting_stdout(out) +... def helloworld(): +... print "hello, world!" + +>>> helloworld() + +>>> out.getvalue() +'hello, world!\n' + +Similar tricks can be used to remove the boilerplate associate with +transactional databases. I think you got the idea, so I will leave +the transactional example as an exercise for the reader. Of course +in Python 2.5 these use cases can also be addressed with the ``with`` +statement. + +Class decorators and decorator factories +-------------------------------------------------------------------- + +Starting from Python 2.6 it is possible to decorate classes. The +decorator module takes advantage of this feature to provide a facility +for writing complex decorator factories. We have already seen examples +of simple decorator factories, implemented as functions returning a +decorator. For more complex situations, it is more convenient to +implement decorator factories as classes returning callable objects +that can be used as signature-preserving decorators. To this aim, +``decorator`` can also be used as a class decorator. Given a class +with a ``.call(self, func, *args, **kw)`` method ``decorator(cls)`` adds a +suitable ``__call__`` method to the class; it raises a TypeError if +the class already has a nontrivial ``__call__`` method. + +To give an example of usage, let me +show a (simplistic) permission system based on classes. +Suppose we have a (Web) framework with the following user classes: + +$$User +$$PowerUser +$$Admin + +Suppose we have a function ``get_userclass`` returning the class of +the user logged in our system: in a Web framework ``get_userclass`` +will read the current user from the environment (i.e. from REMOTE_USER) +and will compare it with a database table to determine her user class. +For the sake of the example, let us use a trivial function: + +$$get_userclass + +We can implement the ``Restricted`` decorator factory as follows: + +$$Restricted +$$PermissionError + +An user can perform different actions according to her class: + +$$Action + +Here is an example of usage:: + + >>> a = Action() + >>> a.view() + >>> a.insert() + Traceback (most recent call last): + ... + PermissionError: User does not have the permission to run insert! + >>> a.delete() + Traceback (most recent call last): + ... + PermissionError: User does not have the permission to run delete! + + +A ``PowerUser`` could call ``.insert`` but not ``.delete``, whereas +and ``Admin`` can call all the methods. + +I could have provided the same functionality by means of a mixin class +(say ``DecoratorMixin``) providing a ``__call__`` method. Within +that design an user should have derived his decorator class from +``DecoratorMixin``. However, `I generally dislike inheritance`_ +and I do not want to force my users to inherit from a class of my +choice. Using the class decorator approach my user is free to use +any class she wants, inheriting from any class she wants, provided +the class provide a proper ``.call`` method and does not provide +a custom ``__call__`` method. In other words, I am trading (less stringent) +interface requirements for (more stringent) inheritance requirements. + +.. _I generally dislike inheritance: http://stacktrace.it/articoli/2008/06/i-pericoli-della-programmazione-con-i-mixin1 + +Dealing with third party decorators: ``new_wrapper`` +------------------------------------------------------------ + +Sometimes you find on the net some cool decorator that you would +like to include in your code. However, more often than not the cool +decorator is not signature-preserving. Therefore you may want an easy way to +upgrade third party decorators to signature-preserving decorators without +having to rewrite them in terms of ``decorator``. To this aim the +``decorator`` module provides an utility function called ``new_wrapper``. +``new_wrapper`` takes a wrapper function with a generic signature and returns +a copy of it with the right signature. +For instance, suppose you have a wrapper function ``wrapper`` (or generically +a callable object) with a "permissive" signature (say ``wrapper(*args, **kw)``) +returned by a third party non signature-preserving decorator; let ``model`` +be the original function, with a stricter signature; then +``new_wrapper(wrapper, model)`` +returns a copy of ``wrapper`` with signature copied from ``model``. +Notice that it is your responsability to make sure that the original +function and the model function have compatibile signature, i.e. that +the signature of the model is stricter (or equivalent) than the signature +of the original function. If not, you will get an error at calling +time, not at decoration time. + +With ``new_wrapper`` at your disposal, it is a breeze to define an utility +to upgrade old-style decorators to signature-preserving decorators: + +$$upgrade_dec + +``tail_recursive`` +------------------------------------------------------------ + +In order to give an example of usage for ``new_wrapper``, I will show a +pretty slick decorator that converts a tail-recursive function in an iterative +function. I have shamelessly stolen the basic idea from Kay Schluehr's recipe +in the Python Cookbook, +http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/496691. + +$$TailRecursive + +$$tail_recursive + +Here the decorator is implemented as a class returning callable +objects. ``upgrade_dec`` converts that class in a factory function +returning functions. +Here is how you apply the upgraded decorator to the good old factorial: + +.. code-block:: python + + @tail_recursive + def factorial(n, acc=1): + "The good old factorial" + if n == 0: return acc + return factorial(n-1, n*acc) + + >>> print factorial(4) + 24 + +This decorator is pretty impressive, and should give you some food for +your mind ;) Notice that there is no recursion limit now, and you can +easily compute ``factorial(1001)`` or larger without filling the stack +frame. Notice also that the decorator will not work on functions which +are not tail recursive, such as + +$$fact + +(a function is tail recursive if it either returns a value without +making a recursive call, or returns directly the result of a recursive +call). + +Caveats and limitations +------------------------------------------- + +The first thing you should be aware of, it the fact that decorators +have a performance penalty. +The worse case is shown by the following example:: + + $ cat performance.sh + python -m timeit -s " + from decorator import decorator + + @decorator + def do_nothing(func, *args, **kw): + return func(*args, **kw) + + @do_nothing + def f(): + pass + " "f()" + + python -m timeit -s " + def f(): + pass + " "f()" + +On my Linux system, using the ``do_nothing`` decorator instead of the +plain function is more than four times slower:: + + $ bash performance.sh + 1000000 loops, best of 3: 1.68 usec per loop + 1000000 loops, best of 3: 0.397 usec per loop + +It should be noted that a real life function would probably do +something more useful than ``f`` here, and therefore in real life the +performance penalty could be completely negligible. As always, the +only way to know if there is +a penalty in your specific use case is to measure it. + +You should be aware that decorators will make your tracebacks +longer and more difficult to understand. Consider this example: + +>>> @tracing +... def f(): +... 1/0 + +Calling ``f()`` will give you a ``ZeroDivisionError``, but since the +function is decorated the traceback will be longer: + +>>> f() +Traceback (most recent call last): + File "", line 1, in ? + f() + File "", line 2, in f + File "", line 4, in tracing + return f(*args, **kw) + File "", line 3, in f + 1/0 +ZeroDivisionError: integer division or modulo by zero + +You see here the inner call to the decorator ``tracing``, which calls +``f(*args, **kw)``, and a reference to ``File "", line 2, in f``. +This latter reference is due to the fact that internally the decorator +module uses ``eval`` to generate the decorated function. Notice that +``eval`` is *not* responsibile for the performance penalty, since is the +called *only once* at function decoration time, and not every time +the decorated function is called. + +Using ``eval`` means that ``inspect.getsource`` will not work for decorated +functions. This means that the usual '??' trick in IPython will give you +the (right on the spot) message +``Dynamically generated function. No source code available.``. This +however is preferable to the situation with regular decorators, where +``inspect.getsource`` gives you the wrapper source code which is probably +not what you want: + +$$identity_dec +$$example + +>>> import inspect +>>> print inspect.getsource(example) + def wrapper(*args, **kw): + return func(*args, **kw) + + +(see bug report 1764286_ for an explanation of what is happening). + +.. _1764286: http://bugs.python.org/issue1764286 + +At present, there is no clean way to avoid ``eval``. A clean solution +would require to change the CPython implementation of functions and +add an hook to make it possible to change their signature directly. +This will happen in future versions of Python (see PEP 362_) and +then the decorator module will become obsolete. + +.. _362: http://www.python.org/dev/peps/pep-0362 + +For debugging purposes, it may be useful to know that the decorator +module also provides a ``getinfo`` utility function which returns a +dictionary containing information about a function. +For instance, for the factorial function we will get + +>>> d = getinfo(factorial) +>>> d['name'] +'factorial' +>>> d['argnames'] +['n', 'acc'] +>>> d['signature'] +'n, acc' +>>> d['defaults'] +(1,) +>>> d['doc'] +'The good old factorial' + +In the present implementation, decorators generated by ``decorator`` +can only be used on user-defined Python functions or methods, not on generic +callable objects, nor on built-in functions, due to limitations of the +``inspect`` module in the standard library. +Also, there is a restriction on the names of the arguments: if try to +call an argument ``_call_`` or ``_func_`` you will get an AssertionError: + +>>> @tracing +... def f(_func_): print f +... +Traceback (most recent call last): + ... +AssertionError: You cannot use _call_ or _func_ as argument names! + +(the existence of these two reserved names is an implementation detail). + +Moreover, the implementation is such that the decorated function contains +a copy of the original function attributes: + +>>> def f(): pass # the original function +>>> f.attr1 = "something" # setting an attribute +>>> f.attr2 = "something else" # setting another attribute + +>>> traced_f = tracing(f) # the decorated function + +>>> traced_f.attr1 +'something' +>>> traced_f.attr2 = "something different" # setting attr +>>> f.attr2 # the original attribute did not change +'something else' + +That's all folks, enjoy! + + +LICENCE +--------------------------------------------- + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met:: + + Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + Redistributions in bytecode form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in + the documentation and/or other materials provided with the + distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH + DAMAGE. + +If you use this software and you are happy with it, consider sending me a +note, just to gratify my ego. On the other hand, if you use this software and +you are unhappy with it, send me a patch! +""" + +import sys, threading +from decorator import * + +def _trace(f, *args, **kw): + print "calling %s with args %s, %s" % (f.func_name, args, kw) + return f(*args, **kw) +def trace(f): + return decorator(_trace, f) + +def delayed(nsec): + def call(proc, *args, **kw): + thread = threading.Timer(nsec, proc, args, kw) + thread.start() + return thread + return decorator(call) + +def identity_dec(func): + def wrapper(*args, **kw): + return func(*args, **kw) + return wrapper + +@identity_dec +def example(): pass + +def _memoize(func, *args, **kw): + # args and kw must be hashable + if kw: + key = args, frozenset(kw.items()) + else: + key = args + cache = func.cache # created at decoration time + if key in cache: + return cache[key] + else: + result = func(*args, **kw) + cache[key] = result + return result + +def memoize(f): + f.cache = {} + return decorator(_memoize, f) + +@decorator +def locked(func, *args, **kw): + lock = getattr_(func, "lock", threading.Lock) + lock.acquire() + try: + result = func(*args, **kw) + finally: + lock.release() + return result + +threaded = delayed(0) # no-delay decorator + +def blocking(not_avail="Not Available"): + def call(f, *args, **kw): + if not hasattr(f, "thread"): # no thread running + def set_result(): f.result = f(*args, **kw) + f.thread = threading.Thread(None, set_result) + f.thread.start() + return not_avail + elif f.thread.isAlive(): + return not_avail + else: # the thread is ended, return the stored result + del f.thread + return f.result + return decorator(call) + +def redirecting_stdout(new_stdout): + def call(func, *args, **kw): + save_stdout = sys.stdout + sys.stdout = new_stdout + try: + result = func(*args, **kw) + finally: + sys.stdout = save_stdout + return result + return decorator(call) + +class User(object): + "Will just be able to see a page" + +class PowerUser(User): + "Will be able to add new pages too" + +class Admin(PowerUser): + "Will be able to delete pages too" + +def get_userclass(): + return User + +class PermissionError(Exception): + pass + +class Restricted(object): + """ + Restrict public methods and functions to a given class of users. + If instantiated twice with the same userclass return the same + object. + """ + _cache = {} + def __new__(cls, userclass): + if userclass in cls._cache: + return cls._cache[userclass] + self = cls._cache[userclass] = super(Restricted, cls).__new__(cls) + self.userclass = userclass + return self + def call(self, func, *args, **kw): + userclass = get_userclass() + if issubclass(userclass, self.userclass): + return func(*args, **kw) + else: + raise PermissionError( + '%s does not have the permission to run %s!' + % (userclass.__name__, func.__name__)) + def __call__(self, func): + return decorator(self.call, func) + + +class Action(object): + @Restricted(User) + def view(self): + pass + + @Restricted(PowerUser) + def insert(self): + pass + + @Restricted(Admin) + def delete(self): + pass + +class TailRecursive(object): + """ + tail_recursive decorator based on Kay Schluehr's recipe + http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/496691 + """ + CONTINUE = object() # sentinel + + def __init__(self, func): + self.func = func + self.firstcall = True + + def __call__(self, *args, **kwd): + try: + if self.firstcall: # start looping + self.firstcall = False + while True: + result = self.func(*args, **kwd) + if result is self.CONTINUE: # update arguments + args, kwd = self.argskwd + else: # last call + break + else: # return the arguments of the tail call + self.argskwd = args, kwd + return self.CONTINUE + except: # reset and re-raise + self.firstcall = True + raise + else: # reset and exit + self.firstcall = True + return result + +tail_recursive = upgrade_dec(TailRecursive) + +def fact(n): # this is not tail-recursive + if n == 0: return 1 + return n * fact(n-1) diff --git a/other.txt b/other.txt new file mode 100755 index 0000000..3eddd5c --- /dev/null +++ b/other.txt @@ -0,0 +1,125 @@ +>>> from examples import deferred + +>>> fac = deferred(0.0) + +>>> results = [] # or use a Queue, if you wish + +>>> def f(x): +... "In real life, should perform some computation on x" +... results.append(x) + +>>> action["user1"] = fac(f) +>>> action["user2"] = fac(f) + +>>> f1("arg1"); print f1.thread +<_Timer(Thread-1, started)> + +>>> f2("arg2"); print f2.thread +<_Timer(Thread-2, started)> + +>>> time.sleep(.4) +>>> print results +['arg1', 'arg2'] + + # + + import time, threading + from decorator import decorator + + @decorator + def blocking(proc, *args, **kw): + thread = getattr(proc, "thread", None) + if thread is None: + proc.thread = threading.Thread(None, proc, args, kw) + proc.thread.start() + elif thread.isAlive(): + raise AccessError("Resource locked!") + else: + proc.thread = None + blocking.copy = True + + # + +>>> from examples import threaded +>>> def f(): +... print "done" + +>>> read1, read2 = blocking(readinput), blocking(readinput) +>>> read1(), read2() +done +done + +Thread factories +--------------------------------------------- + + # + + import threading + + @decorator + def threadfactory(f, *args, **kw): + f.created = getattr(f, "created", 0) + 1 + return threading.Thread(None, f, f.__name__ + str(f.created), args, kw) + + # + +Here the decorator takes a regular function and convert it into a +thread factory. The name of the generated thread is given by +the name of the function plus an integer number, counting how +many threads have been created by the factory. + +>>> from examples import threadfactory + +>>> @threadfactory +... def do_action(): +... "doing something in a separate thread." + + +>>> action1 = do_action() # create a first thread +>>> print action1 + + +>>> action2 = do_action() # create a second thread +>>> action2.start() # start it +>>> print action2 + + +The ``.created`` attribute stores the total number of created threads: + +>>> print do_action.created +2 +The thread object also stores the result of the function call. + + # + + def delayed(nsec): + def call(func, *args, **kw): + def set_result(): thread.result = func(*args, **kw) + thread = threading.Timer(nsec, set_result) + thread.result = "Not available" + thread.start() + return thread + return decorator(call) + + # + +Here is an example of usage:: + + # + + valuelist = [] + + def send_to_external_process(value): + time.sleep(.1) # simulate some time delay + valuelist.append(value) + + @delayed(.2) # give time to the value to reach the external process + def get_from_external_process(): + return valuelist.pop() + + + # + +>>> send_to_external_process("value") +>>> print get_from_external_process() +value diff --git a/performance.sh b/performance.sh new file mode 100644 index 0000000..75e8928 --- /dev/null +++ b/performance.sh @@ -0,0 +1,16 @@ +python -m timeit -s " +from decorator import decorator + +@decorator +def do_nothing(func, *args, **kw): + return func(*args, **kw) + +@do_nothing +def f(): + pass +" "f()" + +python -m timeit -s " +def f(): + pass +" "f()" diff --git a/setup.py b/setup.py new file mode 100644 index 0000000..e6240f6 --- /dev/null +++ b/setup.py @@ -0,0 +1,37 @@ +try: + from setuptools import setup +except ImportError: + from distutils.core import setup + +setup(name='decorator', + version='2.3.2', + description=\ + 'Better living through Python with decorators.', + long_description="""\ +As of now, writing custom decorators correctly requires some experience +and it is not as easy as it could be. For instance, typical implementations +of decorators involve nested functions, and we all know +that flat is better than nested. Moreover, typical implementations +of decorators do not preserve the signature of decorated functions, +thus confusing both documentation tools and developers. + +The aim of the decorator module it to simplify the usage of decorators +for the average programmer, and to popularize decorators usage giving +examples of useful decorators, such as memoize, tracing, +redirecting_stdout, locked, etc.""", + author='Michele Simionato', + author_email='michele.simionato@gmail.com', + url='http://www.phyast.pitt.edu/~micheles/python/documentation.html', + license="BSD License", + py_modules = ['decorator'], + keywords="decorators generic utility", + classifiers=['Development Status :: 5 - Production/Stable', + 'Intended Audience :: Developers', + 'License :: OSI Approved :: BSD License', + 'Natural Language :: English', + 'Operating System :: OS Independent', + 'Programming Language :: Python', + 'Topic :: Software Development :: Libraries', + 'Topic :: Utilities'], + zip_safe=False) + diff --git a/util.py b/util.py new file mode 100755 index 0000000..80e9037 --- /dev/null +++ b/util.py @@ -0,0 +1,14 @@ +""" +A few useful decorators +""" + +import sys, time +from decorator import decorator + +@decorator +def traced(func, *args, **kw): + t1 = time.time() + res = func(*args,**kw) + t2 = time.time() + print >> sys.stderr, func.__name__, args, 'TIME:', t2-t1 + return res -- cgit v1.2.1 From 49f5428fcbdc2ad712eddd2ce131a4540364dac7 Mon Sep 17 00:00:00 2001 From: "michele.simionato" Date: Tue, 9 Dec 2008 07:15:54 +0000 Subject: Many improvements --- decorator.py | 35 +++++++++------- documentation.py | 126 +++++++++++++++++-------------------------------------- 2 files changed, 58 insertions(+), 103 deletions(-) diff --git a/decorator.py b/decorator.py index e9a35e0..39debfa 100755 --- a/decorator.py +++ b/decorator.py @@ -93,25 +93,28 @@ def makefn(src, funcdata, save_source=True, **evaldict): func = evaldict[name] return funcdata.update(func, __source__=src) -def decorator(caller, func=None): +def decorator_apply(caller, func): + "decorator.apply(caller, func) is akin to decorator(caller)(func)" + fd = FuncData(func) + name = fd.name + signature = fd.signature + for arg in signature.split(','): + argname = arg.strip(' *') + assert not argname in('_func_', '_call_'), ( + '%s is a reserved argument name!' % argname) + src = """def %(name)s(%(signature)s): + return _call_(_func_, %(signature)s)""" % locals() + return makefn(src, fd, save_source=False, _func_=func, _call_=caller) + +def decorator(caller): """ - decorator(caller) converts a caller function into a decorator; - decorator(caller, func) is akin to decorator(caller)(func). + decorator(caller) converts a caller function into a decorator. """ - if func: - fd = FuncData(func) - name = fd.name - signature = fd.signature - for arg in signature.split(','): - argname = arg.strip(' *') - assert not argname in('_func_', '_call_'), ( - '%s is a reserved argument name!' % argname) - src = """def %(name)s(%(signature)s): - return _call_(_func_, %(signature)s)""" % locals() - return makefn(src, fd, save_source=False, _func_=func, _call_=caller) - src = 'def %s(func): return decorator(caller, func)' % caller.__name__ + src = 'def %s(func): return appl(caller, func)' % caller.__name__ return makefn(src, FuncData(caller), save_source=False, - caller=caller, decorator=decorator) + caller=caller, appl=decorator_apply) + +decorator.apply = decorator_apply @decorator def deprecated(func, *args, **kw): diff --git a/documentation.py b/documentation.py index 3d5f88a..dadb231 100644 --- a/documentation.py +++ b/documentation.py @@ -14,12 +14,13 @@ The ``decorator`` module Introduction ------------------------------------------------ -Python 2.4 decorators are an interesting example of why syntactic sugar -matters: in principle, their introduction changed nothing, since they do -not provide any new functionality which was not already present in the -language; in practice, their introduction has significantly changed the way -we structure our programs in Python. I believe the change is for the best, -and that decorators are a great idea since: +Python decorators are an interesting example of why syntactic sugar +matters. In principle, their introduction in Python 2.4 changed +nothing, since they do not provide any new functionality which was not +already present in the language; in practice, their introduction has +significantly changed the way we structure our programs in Python. I +believe the change is for the best, and that decorators are a great +idea since: * decorators help reducing boilerplate code; * decorators help separation of concerns; @@ -145,12 +146,15 @@ First of all, you must import ``decorator``: >>> from decorator import decorator -Then you must define an helper function with signature ``(f, *args, **kw)`` +Then you must define a helper function with signature ``(f, *args, **kw)`` which calls the original function ``f`` with arguments ``args`` and ``kw`` and implements the tracing capability: $$_trace +At this point you can define your decorator in terms of the helper function +via ``decorator.apply``: + $$trace Therefore, you can write the following: @@ -192,7 +196,8 @@ That includes even functions with exotic signatures like the following: calling exotic_signature with args ((1, 2),), {} 3 -Notice that exotic signatures have been disabled in Python 3.0. +Notice that the support for exotic signatures has been deprecated +in Python 2.6 and removed in Python 3.0. ``decorator`` is a decorator --------------------------------------------- @@ -274,38 +279,6 @@ tuple(kwargs.iteritems()))`` as key for the memoize dictionary. Notice that in general it is impossible to memoize correctly something that depends on mutable arguments. -``locked`` ---------------------------------------------------------------- - -There are good use cases for decorators is in multithreaded programming. -For instance, a ``locked`` decorator can remove the boilerplate -for acquiring/releasing locks [#]_. - -.. [#] In Python 2.5, the preferred way to manage locking is via - the ``with`` statement: http://docs.python.org/lib/with-locks.html - -To show an example of usage, suppose one wants to write some data to -an external resource which can be accessed by a single user at once -(for instance a printer). Then the access to the writing function must -be locked: - -.. code-block:: python - - import time - - datalist = [] # for simplicity the written data are stored into a list. - - @locked - def write(data): - "Writing to a sigle-access resource" - time.sleep(1) - datalist.append(data) - - -Since the writing function is locked, we are guaranteed that at any given time -there is at most one writer. An example multithreaded program that invokes -``write`` and prints the datalist is shown in the next section. - ``delayed`` and ``threaded`` -------------------------------------------- @@ -350,8 +323,28 @@ to deserve a name: threaded = delayed(0) Threaded procedures will be executed in a separated thread as soon -as they are called. Here is an example using the ``write`` -routine defined before: +as they are called. Here is an example. + +Suppose one wants to write some data to +an external resource which can be accessed by a single user at once +(for instance a printer). Then the access to the writing function must +be locked: + +.. code-block:: python + + import time + + datalist = [] # for simplicity the written data are stored into a list. + + def write(data): + "Writing to a sigle-access resource" + with threading.Lock(): + time.sleep(1) + datalist.append(data) + + +Since the writing function is locked, we are guaranteed that at any given time +there is at most one writer. Here is an example. >>> @threaded ... def writedata(data): @@ -406,35 +399,6 @@ Please wait ... >>> print read_data() some data -``redirecting_stdout`` -------------------------------------------- - -Decorators help in removing the boilerplate associated to ``try .. finally`` -blocks. We saw the case of ``locked``; here is another example: - -$$redirecting_stdout - -Here is an example of usage: - ->>> from StringIO import StringIO - ->>> out = StringIO() - ->>> @redirecting_stdout(out) -... def helloworld(): -... print "hello, world!" - ->>> helloworld() - ->>> out.getvalue() -'hello, world!\n' - -Similar tricks can be used to remove the boilerplate associate with -transactional databases. I think you got the idea, so I will leave -the transactional example as an exercise for the reader. Of course -in Python 2.5 these use cases can also be addressed with the ``with`` -statement. - Class decorators and decorator factories -------------------------------------------------------------------- @@ -529,9 +493,8 @@ of the original function. If not, you will get an error at calling time, not at decoration time. With ``new_wrapper`` at your disposal, it is a breeze to define an utility -to upgrade old-style decorators to signature-preserving decorators: +to upgrade old-style decorators to signature-preserving decorators. -$$upgrade_dec ``tail_recursive`` ------------------------------------------------------------ @@ -760,7 +723,7 @@ def _trace(f, *args, **kw): print "calling %s with args %s, %s" % (f.func_name, args, kw) return f(*args, **kw) def trace(f): - return decorator(_trace, f) + return decorator.apply(_trace, f) def delayed(nsec): def call(proc, *args, **kw): @@ -793,7 +756,7 @@ def _memoize(func, *args, **kw): def memoize(f): f.cache = {} - return decorator(_memoize, f) + return decorator.apply(_memoize, f) @decorator def locked(func, *args, **kw): @@ -821,17 +784,6 @@ def blocking(not_avail="Not Available"): return f.result return decorator(call) -def redirecting_stdout(new_stdout): - def call(func, *args, **kw): - save_stdout = sys.stdout - sys.stdout = new_stdout - try: - result = func(*args, **kw) - finally: - sys.stdout = save_stdout - return result - return decorator(call) - class User(object): "Will just be able to see a page" @@ -869,7 +821,7 @@ class Restricted(object): '%s does not have the permission to run %s!' % (userclass.__name__, func.__name__)) def __call__(self, func): - return decorator(self.call, func) + return decorator.apply(self.call, func) class Action(object): -- cgit v1.2.1 From d8093a86cc3b49f3d13e8616794731a17b8b866b Mon Sep 17 00:00:00 2001 From: "michele.simionato" Date: Tue, 9 Dec 2008 16:40:07 +0000 Subject: Lots of improvements to decorator 3.0 --- decorator.py | 205 +++++++++++++++++++--------- documentation.py | 402 ++++++++++++++++++++++++++++++------------------------- 2 files changed, 368 insertions(+), 239 deletions(-) diff --git a/decorator.py b/decorator.py index 39debfa..1f1607b 100755 --- a/decorator.py +++ b/decorator.py @@ -1,4 +1,4 @@ -########################## LICENCE ############################### +########################## LICENCE ############################### ## Redistributions of source code must retain the above copyright ## notice, this list of conditions and the following disclaimer. @@ -25,35 +25,36 @@ Decorator module, see http://pypi.python.org/pypi/decorator for the documentation. """ -## The basic trick is to generate the source code for the decorated function -## with the right signature and to evaluate it. +__all__ = ["decorator", "FunctionMaker", "getinfo", "new_wrapper"] -__all__ = ["decorator", "makefn", "getsignature", "upgrade_dec"] - -import os, sys, re, inspect, warnings -from tempfile import mkstemp +import os, sys, re, inspect, warnings, tempfile DEF = re.compile('\s*def\s*([_\w][_\w\d]*)\s*\(') +# helper def _callermodule(level=2): return sys._getframe(level).f_globals.get('__name__', '?') - -def getsignature(func): - "Return the signature of a function as a string" - argspec = inspect.getargspec(func) - return inspect.formatargspec(formatvalue=lambda val: "", *argspec)[1:-1] -class FuncData(object): +# basic functionality +class FunctionMaker(object): + """ + An object with the ability to create functions with a given signature. + It has attributes name, doc, module, signature, defaults, dict and + methods update and make. + """ def __init__(self, func=None, name=None, signature=None, defaults=None, doc=None, module=None, funcdict=None): if func: # func can also be a class or a callable self.name = func.__name__ + if self.name == '': # small hack for lambda functions + self.name = '_lambda_' self.doc = func.__doc__ self.module = func.__module__ if inspect.isfunction(func): - self.signature = getsignature(func) + self.signature = inspect.formatargspec( + formatvalue=lambda val: "", *inspect.getargspec(func))[1:-1] self.defaults = func.func_defaults - self.dict = func.__dict__ + self.dict = func.__dict__.copy() if name: self.name = name if signature: @@ -66,67 +67,151 @@ class FuncData(object): self.module = module if funcdict: self.dict = funcdict + self.name, self.signature # check existence required attributes def update(self, func, **kw): - func.__name__ = getattr(self, 'name', 'noname') + "Update the signature of func with the data in self" + func.__name__ = self.name func.__doc__ = getattr(self, 'doc', None) func.__dict__ = getattr(self, 'dict', {}) func.func_defaults = getattr(self, 'defaults', None) func.__module__ = getattr(self, 'module', _callermodule()) func.__dict__.update(kw) + + def make(self, templ, save_source=False, **evaldict): + "Make a new function from a given template and update the signature" + src = templ % vars(self) # expand name and signature + mo = DEF.match(src) + if mo is None: + raise SyntaxError('not a valid function template\n%s' % src) + name = mo.group(1) # extract the function name + reserved_names = set([name] + [ + arg.strip(' *') for arg in self.signature.split(',')]) + s = '' + for n, v in evaldict.items(): + if inspect.isfunction(v): + s += '# %s=\n' % (n, v.__module__, v.__name__) + if n in reserved_names: + raise NameError('%s is overridden in\n%s' % (n, src)) + source = s + src + if not source.endswith('\n'): # add a newline just for safety + source += '\n' + if save_source: + fhandle, fname = tempfile.mkstemp() + os.write(fhandle, source) + os.close(fhandle) + else: + fname = '?' + code = compile(source, fname, 'single') + exec code in evaldict + func = evaldict[name] + self.update(func, __source__=source) return func - - def __getitem__(self, name): - return getattr(self, name) - -def makefn(src, funcdata, save_source=True, **evaldict): - src += os.linesep # add a newline just for safety - name = DEF.match(src).group(1) # extract the function name from the source - if save_source: - fhandle, fname = mkstemp() - os.write(fhandle, src) - os.close(fhandle) - else: - fname = '?' - code = compile(src, fname, 'single') - exec code in evaldict - func = evaldict[name] - return funcdata.update(func, __source__=src) - -def decorator_apply(caller, func): - "decorator.apply(caller, func) is akin to decorator(caller)(func)" - fd = FuncData(func) - name = fd.name - signature = fd.signature - for arg in signature.split(','): - argname = arg.strip(' *') - assert not argname in('_func_', '_call_'), ( - '%s is a reserved argument name!' % argname) + +def decorator_wrap(caller, func): + "Decorate a function with a caller" + fun = FunctionMaker(func) src = """def %(name)s(%(signature)s): - return _call_(_func_, %(signature)s)""" % locals() - return makefn(src, fd, save_source=False, _func_=func, _call_=caller) + return _call_(_func_, %(signature)s)""" + return fun.make(src, _func_=func, _call_=caller) + +def decorator_apply(dec, func): + "Decorate a function using a signature-non-preserving decorator" + fun = FunctionMaker(func) + src = '''def %(name)s(%(signature)s): + return decorated(%(signature)s)''' + return fun.make(src, decorated=dec(func)) def decorator(caller): - """ - decorator(caller) converts a caller function into a decorator. - """ - src = 'def %s(func): return appl(caller, func)' % caller.__name__ - return makefn(src, FuncData(caller), save_source=False, - caller=caller, appl=decorator_apply) + "decorator(caller) converts a caller function into a decorator" + fun = FunctionMaker(caller) + first_arg = fun.signature.split(',')[0] + src = 'def %s(%s): return _call_(caller, %s)' % ( + caller.__name__, first_arg, first_arg) + return fun.make(src, caller=caller, _call_=decorator_wrap) +decorator.wrap = decorator_wrap decorator.apply = decorator_apply +###################### deprecated functionality ######################### + @decorator def deprecated(func, *args, **kw): "A decorator for deprecated functions" - warnings.warn('Calling the deprecated function %r' % func.__name__, - DeprecationWarning, stacklevel=3) + warnings.warn( + ('Calling the deprecated function %r\n' + 'Downgrade to decorator 2.3 if you want to use this functionality') + % func.__name__, DeprecationWarning, stacklevel=3) return func(*args, **kw) -def upgrade_dec(dec): - def new_dec(func): - fd = FuncData(func) - src = '''def %(name)s(%(signature)s): - return decorated(%(signature)s)''' % fd - return makefn(src, fd, save_source=False, decorated=dec(func)) - return FuncData(dec).update(new_dec) +@deprecated +def getinfo(func): + """ + Returns an info dictionary containing: + - name (the name of the function : str) + - argnames (the names of the arguments : list) + - defaults (the values of the default arguments : tuple) + - signature (the signature : str) + - doc (the docstring : str) + - module (the module name : str) + - dict (the function __dict__ : str) + + >>> def f(self, x=1, y=2, *args, **kw): pass + + >>> info = getinfo(f) + + >>> info["name"] + 'f' + >>> info["argnames"] + ['self', 'x', 'y', 'args', 'kw'] + + >>> info["defaults"] + (1, 2) + + >>> info["signature"] + 'self, x, y, *args, **kw' + """ + assert inspect.ismethod(func) or inspect.isfunction(func) + regargs, varargs, varkwargs, defaults = inspect.getargspec(func) + argnames = list(regargs) + if varargs: + argnames.append(varargs) + if varkwargs: + argnames.append(varkwargs) + signature = inspect.formatargspec(regargs, varargs, varkwargs, defaults, + formatvalue=lambda value: "")[1:-1] + return dict(name=func.__name__, argnames=argnames, signature=signature, + defaults = func.func_defaults, doc=func.__doc__, + module=func.__module__, dict=func.__dict__, + globals=func.func_globals, closure=func.func_closure) + +@deprecated +def update_wrapper(wrapper, model, infodict=None): + "A replacement for functools.update_wrapper" + infodict = infodict or getinfo(model) + wrapper.__name__ = infodict['name'] + wrapper.__doc__ = infodict['doc'] + wrapper.__module__ = infodict['module'] + wrapper.__dict__.update(infodict['dict']) + wrapper.func_defaults = infodict['defaults'] + wrapper.undecorated = model + return wrapper + +@deprecated +def new_wrapper(wrapper, model): + """ + An improvement over functools.update_wrapper. The wrapper is a generic + callable object. It works by generating a copy of the wrapper with the + right signature and by updating the copy, not the original. + Moreovoer, 'model' can be a dictionary with keys 'name', 'doc', 'module', + 'dict', 'defaults'. + """ + if isinstance(model, dict): + infodict = model + else: # assume model is a function + infodict = getinfo(model) + assert not '_wrapper_' in infodict["argnames"], ( + '"_wrapper_" is a reserved argument name!') + src = "lambda %(signature)s: _wrapper_(%(signature)s)" % infodict + funcopy = eval(src, dict(_wrapper_=wrapper)) + return update_wrapper(funcopy, model, infodict) diff --git a/documentation.py b/documentation.py index dadb231..a73693a 100644 --- a/documentation.py +++ b/documentation.py @@ -35,7 +35,7 @@ we all know that flat is better than nested. The aim of the ``decorator`` module it to simplify the usage of decorators for the average programmer, and to popularize decorators usage giving examples of useful decorators, such as ``memoize``, -``tracing``, ``redirecting_stdout``, ``locked``, etc. +``tracing``, etc. The core of this module is a decorator factory called ``decorator``. All decorators discussed here are built as simple recipes on top @@ -77,41 +77,32 @@ the issue. Statement of the problem ------------------------------ -Suppose you want to trace a function: this is a typical use case -for a decorator and you can find in many places code like this: +A typical decorator is a decorator to memoize functions. +Such a decorator works by caching +the result of a function call in a dictionary, so that the next time +the function is called with the same input parameters the result is retrieved +from the cache and not recomputed. There are many implementations of +``memoize`` in http://www.python.org/moin/PythonDecoratorLibrary, +but they do not preserve the signature. +A simple implementation for Python 2.5 could be the following: -.. code-block:: python +$$memoize25 - try: - from functools import update_wrapper - except ImportError: # using Python version < 2.5 - def decorator_trace(f): - def newf(*args, **kw): - print "calling %s with args %s, %s" % (f.__name__, args, kw) - return f(*args, **kw) - newf.__name__ = f.__name__ - newf.__dict__.update(f.__dict__) - newf.__doc__ = f.__doc__ - newf.__module__ = f.__module__ - return newf - else: # using Python 2.5+ - def decorator_trace(f): - def newf(*args, **kw): - print "calling %s with args %s, %s" % (f.__name__, args, kw) - return f(*args, **kw) - return update_wrapper(newf, f) +Here we used the ``functools.update_wrapper`` utility, which has +been added in Python 2.5 to simplify the definition of decorators. The implementation above works in the sense that the decorator can accept functions with generic signatures; unfortunately this implementation does *not* define a signature-preserving decorator, since in -general ``decorator_trace`` returns a function with a +general ``memoize25`` returns a function with a *different signature* from the original function. Consider for instance the following case: ->>> @decorator_trace +>>> @memoize25 ... def f1(x): -... pass +... time.sleep(1) +... return x Here the original function takes a single argument named ``x``, but the decorated function takes any number of arguments and @@ -139,9 +130,7 @@ The solution is to provide a generic factory of generators, which hides the complexity of making signature-preserving decorators from the application programmer. The ``decorator`` factory allows to define decorators without the need to use nested functions -or classes. As an example, here is how you can define -``decorator_trace``. - +or classes. First of all, you must import ``decorator``: >>> from decorator import decorator @@ -150,14 +139,43 @@ Then you must define a helper function with signature ``(f, *args, **kw)`` which calls the original function ``f`` with arguments ``args`` and ``kw`` and implements the tracing capability: +$$_memoize + +At this point you can define your decorator by means of ``decorator.wrap``: + +$$memoize + +Here is a test of usage: + +>>> @memoize +... def heavy_computation(): +... time.sleep(2) +... return "done" + +>>> print heavy_computation() # the first time it will take 2 seconds +done + +>>> print heavy_computation() # the second time it will be instantaneous +done + +The signature of ``heavy_computation`` is the one you would expect: + +>>> print getargspec(heavy_computation) +([], None, None, None) + +Notice that in general it is impossible to memoize correctly something +that depends on mutable arguments. + +A ``trace`` decorator +------------------------------------------------------ + +As an additional example, here is how you can define a ``trace`` decorator. + $$_trace -At this point you can define your decorator in terms of the helper function -via ``decorator.apply``: - $$trace -Therefore, you can write the following: +Then, you can write the following: >>> @trace ... def f1(x): @@ -187,7 +205,7 @@ calling f with args (0, 3, 2), {} That includes even functions with exotic signatures like the following: ->>> @decorator(trace) +>>> @trace ... def exotic_signature((x, y)=(1,2)): return x+y >>> print getargspec(exotic_signature) @@ -202,12 +220,9 @@ in Python 2.6 and removed in Python 3.0. ``decorator`` is a decorator --------------------------------------------- -``decorator`` is able to convert the helper function into a -signature-preserving decorator -object, i.e is a callable object that takes a function and returns a -decorated function with the same signature of the original function. - -The ``decorator`` factory itself can be considered as a signature-changing +The ``decorator`` module provides an easy shortcut to convert +the helper function into a signature-preserving decorator: the +``decorator`` function itself, which can be considered as a signature-changing decorator, just as ``classmethod`` and ``staticmethod``. However, ``classmethod`` and ``staticmethod`` return generic objects which are not callable, while ``decorator`` returns @@ -219,11 +234,21 @@ Therefore, you can write ... print "calling %s with args %s, %s" % (f.func_name, args, kw) ... return f(*args, **kw) -and this idiom is actually redefining ``tracing`` to be a decorator. +instead of + +.. code-block:: python + + def _tracing(f, *args, **kw): + print "calling %s with args %s, %s" % (f.func_name, args, kw) + return f(*args, **kw) + + def tracing(f): + return decorator.wrap(_tracing, f) + We can easily check that the signature has changed: >>> print getargspec(tracing) -(['func'], None, None, None) +(['f'], None, None, None) Therefore now ``tracing`` can be used as a decorator and the following will work: @@ -234,51 +259,9 @@ the following will work: >>> func() calling func with args (), {} -BTW, you may use the decorator on lambda functions too: - ->>> tracing(lambda : None)() -calling with args (), {} - For the rest of this document, I will discuss examples of useful decorators built on top of ``decorator``. -``memoize`` ---------------------------------------------------------- - -This decorator implements the ``memoize`` pattern, i.e. it caches -the result of a function in a dictionary, so that the next time -the function is called with the same input parameters the result is retrieved -from the cache and not recomputed. There are many implementations of -``memoize`` in http://www.python.org/moin/PythonDecoratorLibrary, -but they do not preserve the signature. - -$$_memoize - -$$memoize - -Here is a test of usage: - ->>> @memoize -... def heavy_computation(): -... time.sleep(2) -... return "done" - ->>> print heavy_computation() # the first time it will take 2 seconds -done - ->>> print heavy_computation() # the second time it will be instantaneous -done - -As an exercise, try to implement ``memoize`` *properly* without the -``decorator`` factory. - -For sake of semplicity, my implementation only works for functions -with no keyword arguments. One can relax this requirement, and allow -keyword arguments in the signature, for instance by using ``(args, -tuple(kwargs.iteritems()))`` as key for the memoize dictionary. -Notice that in general it is impossible to memoize correctly something -that depends on mutable arguments. - ``delayed`` and ``threaded`` -------------------------------------------- @@ -336,12 +319,7 @@ be locked: datalist = [] # for simplicity the written data are stored into a list. - def write(data): - "Writing to a sigle-access resource" - with threading.Lock(): - time.sleep(1) - datalist.append(data) - +$$write Since the writing function is locked, we are guaranteed that at any given time there is at most one writer. Here is an example. @@ -399,20 +377,14 @@ Please wait ... >>> print read_data() some data -Class decorators and decorator factories +decorator factories -------------------------------------------------------------------- -Starting from Python 2.6 it is possible to decorate classes. The -decorator module takes advantage of this feature to provide a facility -for writing complex decorator factories. We have already seen examples +We have already seen examples of simple decorator factories, implemented as functions returning a decorator. For more complex situations, it is more convenient to implement decorator factories as classes returning callable objects -that can be used as signature-preserving decorators. To this aim, -``decorator`` can also be used as a class decorator. Given a class -with a ``.call(self, func, *args, **kw)`` method ``decorator(cls)`` adds a -suitable ``__call__`` method to the class; it raises a TypeError if -the class already has a nontrivial ``__call__`` method. +that can be used as signature-preserving decorators. To give an example of usage, let me show a (simplistic) permission system based on classes. @@ -452,7 +424,6 @@ Here is an example of usage:: ... PermissionError: User does not have the permission to run delete! - A ``PowerUser`` could call ``.insert`` but not ``.delete``, whereas and ``Admin`` can call all the methods. @@ -469,7 +440,7 @@ interface requirements for (more stringent) inheritance requirements. .. _I generally dislike inheritance: http://stacktrace.it/articoli/2008/06/i-pericoli-della-programmazione-con-i-mixin1 -Dealing with third party decorators: ``new_wrapper`` +Dealing with third party decorators: ``decorator.apply`` ------------------------------------------------------------ Sometimes you find on the net some cool decorator that you would @@ -477,29 +448,10 @@ like to include in your code. However, more often than not the cool decorator is not signature-preserving. Therefore you may want an easy way to upgrade third party decorators to signature-preserving decorators without having to rewrite them in terms of ``decorator``. To this aim the -``decorator`` module provides an utility function called ``new_wrapper``. -``new_wrapper`` takes a wrapper function with a generic signature and returns -a copy of it with the right signature. -For instance, suppose you have a wrapper function ``wrapper`` (or generically -a callable object) with a "permissive" signature (say ``wrapper(*args, **kw)``) -returned by a third party non signature-preserving decorator; let ``model`` -be the original function, with a stricter signature; then -``new_wrapper(wrapper, model)`` -returns a copy of ``wrapper`` with signature copied from ``model``. -Notice that it is your responsability to make sure that the original -function and the model function have compatibile signature, i.e. that -the signature of the model is stricter (or equivalent) than the signature -of the original function. If not, you will get an error at calling -time, not at decoration time. - -With ``new_wrapper`` at your disposal, it is a breeze to define an utility -to upgrade old-style decorators to signature-preserving decorators. - - -``tail_recursive`` ------------------------------------------------------------- +``decorator`` module provides an utility function +``decorator.apply(third_party_decorator, func)``. -In order to give an example of usage for ``new_wrapper``, I will show a +In order to give an example of usage, I will show a pretty slick decorator that converts a tail-recursive function in an iterative function. I have shamelessly stolen the basic idea from Kay Schluehr's recipe in the Python Cookbook, @@ -507,11 +459,11 @@ http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/496691. $$TailRecursive +Here the decorator is implemented as a class returning callable +objects. + $$tail_recursive -Here the decorator is implemented as a class returning callable -objects. ``upgrade_dec`` converts that class in a factory function -returning functions. Here is how you apply the upgraded decorator to the good old factorial: .. code-block:: python @@ -599,12 +551,12 @@ ZeroDivisionError: integer division or modulo by zero You see here the inner call to the decorator ``tracing``, which calls ``f(*args, **kw)``, and a reference to ``File "", line 2, in f``. This latter reference is due to the fact that internally the decorator -module uses ``eval`` to generate the decorated function. Notice that -``eval`` is *not* responsibile for the performance penalty, since is the +module uses ``exec`` to generate the decorated function. Notice that +``exec`` is *not* responsibile for the performance penalty, since is the called *only once* at function decoration time, and not every time the decorated function is called. -Using ``eval`` means that ``inspect.getsource`` will not work for decorated +Using ``exec`` means that ``inspect.getsource`` will not work for decorated functions. This means that the usual '??' trick in IPython will give you the (right on the spot) message ``Dynamically generated function. No source code available.``. This @@ -622,51 +574,59 @@ $$example (see bug report 1764286_ for an explanation of what is happening). +Actually, starting from release 3.0, the decorator module, adds +a ``__source__`` attribute to the decorated function, therefore +you can get the code which is executed: + +>>> print f.__source__ +# _call_= +# _func_= +def f(): + return _call_(_func_, ) + .. _1764286: http://bugs.python.org/issue1764286 -At present, there is no clean way to avoid ``eval``. A clean solution +The generated function is a closure depending on the the caller +``_call_`` and the original function ``_func_``. For debugging convenience +you get the names of the moduled where they are defined in a comment: +in this example they are defined in the ``__main__`` module. + +At present, there is no clean way to avoid ``exec``. A clean solution would require to change the CPython implementation of functions and add an hook to make it possible to change their signature directly. -This will happen in future versions of Python (see PEP 362_) and -then the decorator module will become obsolete. +That could happen in future versions of Python (see PEP 362_) and +then the decorator module would become obsolete. However, at present, +even in Python 3.0 it is impossible to change the function signature +directly, therefore the ``decorator`` module is still useful (this is +the reason why I am releasing version 3.0). .. _362: http://www.python.org/dev/peps/pep-0362 -For debugging purposes, it may be useful to know that the decorator -module also provides a ``getinfo`` utility function which returns a -dictionary containing information about a function. -For instance, for the factorial function we will get - ->>> d = getinfo(factorial) ->>> d['name'] -'factorial' ->>> d['argnames'] -['n', 'acc'] ->>> d['signature'] -'n, acc' ->>> d['defaults'] -(1,) ->>> d['doc'] -'The good old factorial' - In the present implementation, decorators generated by ``decorator`` can only be used on user-defined Python functions or methods, not on generic callable objects, nor on built-in functions, due to limitations of the ``inspect`` module in the standard library. -Also, there is a restriction on the names of the arguments: if try to -call an argument ``_call_`` or ``_func_`` you will get an AssertionError: + +Moreover, you can decorate anonymous functions: + +>>> tracing(lambda : None)() +calling with args (), {} + +There is a restriction on the names of the arguments: for instance, +if try to call an argument ``_call_`` or ``_func_`` +you will get a ``NameError``: >>> @tracing ... def f(_func_): print f ... Traceback (most recent call last): ... -AssertionError: You cannot use _call_ or _func_ as argument names! +NameError: _func_ is overridden in +def f(_func_): + return _call_(_func_, _func_) -(the existence of these two reserved names is an implementation detail). - -Moreover, the implementation is such that the decorated function contains +Finally, the implementation is such that the decorated function contains a copy of the original function attributes: >>> def f(): pass # the original function @@ -681,8 +641,67 @@ a copy of the original function attributes: >>> f.attr2 # the original attribute did not change 'something else' -That's all folks, enjoy! - +The ``FunctionMaker`` class +--------------------------------------------------------------- + +The public API of the ``decorator`` module consists in the +``decorator`` function and its two attributes ``decorator.wrap`` and +``decorator.apply``. Internally, the functionality is implemented via +a ``FunctionMaker`` class which is able to generate on the fly +functions with a given name and signature. You should not need to +resort to ``FunctionMaker`` when writing ordinary decorators, but it +is interesting to know how the module works internally, so I have +decided to add this paragraph. Notice that while I do not have plan +to change or remove the functionality provided in the +``FunctionMaker`` class, I do not guarantee that it will stay +unchanged forever. On the other hand, the functionality provided by +``decorator`` has been there from version 0.1 and it is guaranteed to +stay there forever. +``FunctionMaker`` takes the name and the signature of a function in +input, or a whole function. Here is an example of how to +restrict the signature of a function: + +>>> def f(*args, **kw): +... print args, kw + +>>> f1 = FunctionMaker(name="f1", signature="a,b").make(''' +... def %(name)s(%(signature)s): +... f(%(signature)s)''', f=f) + +>>> f1(1,2) +(1, 2) {} + +The utility ``decorator.wrap`` instead takes a function in input and +returns a new function; it is defined as follows: + +$$decorator_wrap + +Backward compatibility notes +--------------------------------------------------------------- + +Version 3.0 is a complete rewrite of the original implementation. +It is mostly compatible with the past, a part for a few differences. + +The utilites ``get_info`` and ``new_wrapper``, available +in the 2.X versions, have been deprecated and they will be removed +in the future. For the moment, using them raises a ``DeprecationWarning``. +``get_info`` has been removed since it was little used and since it had +to be changed anyway to work with Python 3.0; ``new_wrapper`` has been +removed since it was useless: its major use case (converting +signature changing decorators to signature preserving decorators) +has been subsumed by ``decorator.apply`` +and the other use case can be managed with the ``FunctionMaker``. + +Finally ``decorator`` cannot be used as a class decorator and the +`functionality introduced in version 2.3`_ has been removed. That +means that in order to define decorator factories with classes you +need to override the ``__call__`` method explicitly (no magic anymore). + +All these changes should not cause any trouble, since they were +all rarely used features. Should you have trouble, you are invited to +downgrade to the 2.3 version. + +.. _functionality introduced in version 2.3: http://www.phyast.pitt.edu/~micheles/python/documentation.html#class-decorators-and-decorator-factories LICENCE --------------------------------------------- @@ -715,22 +734,25 @@ If you use this software and you are happy with it, consider sending me a note, just to gratify my ego. On the other hand, if you use this software and you are unhappy with it, send me a patch! """ - -import sys, threading +from __future__ import with_statement +import sys, threading, time, functools from decorator import * +decorator_wrap = decorator.wrap + def _trace(f, *args, **kw): print "calling %s with args %s, %s" % (f.func_name, args, kw) return f(*args, **kw) + def trace(f): - return decorator.apply(_trace, f) + return decorator.wrap(_trace, f) def delayed(nsec): - def call(proc, *args, **kw): + def _delayed(proc, *args, **kw): thread = threading.Timer(nsec, proc, args, kw) thread.start() return thread - return decorator(call) + return decorator(_delayed) def identity_dec(func): def wrapper(*args, **kw): @@ -750,28 +772,32 @@ def _memoize(func, *args, **kw): if key in cache: return cache[key] else: - result = func(*args, **kw) - cache[key] = result + cache[key] = result = func(*args, **kw) return result def memoize(f): f.cache = {} - return decorator.apply(_memoize, f) - -@decorator -def locked(func, *args, **kw): - lock = getattr_(func, "lock", threading.Lock) - lock.acquire() - try: - result = func(*args, **kw) - finally: - lock.release() - return result + return decorator.wrap(_memoize, f) + +def memoize25(func): + func.cache = {} + def memoize(*args, **kw): + if kw: + key = args, frozenset(kw.items()) + else: + key = args + cache = func.cache # created at decoration time + if key in cache: + return cache[key] + else: + cache[key] = result = func(*args, **kw) + return result + return functools.update_wrapper(memoize, func) threaded = delayed(0) # no-delay decorator def blocking(not_avail="Not Available"): - def call(f, *args, **kw): + def _blocking(f, *args, **kw): if not hasattr(f, "thread"): # no thread running def set_result(): f.result = f(*args, **kw) f.thread = threading.Thread(None, set_result) @@ -782,7 +808,7 @@ def blocking(not_avail="Not Available"): else: # the thread is ended, return the stored result del f.thread return f.result - return decorator(call) + return decorator(_blocking) class User(object): "Will just be able to see a page" @@ -821,8 +847,7 @@ class Restricted(object): '%s does not have the permission to run %s!' % (userclass.__name__, func.__name__)) def __call__(self, func): - return decorator.apply(self.call, func) - + return decorator.wrap(self.call, func) class Action(object): @Restricted(User) @@ -868,8 +893,27 @@ class TailRecursive(object): self.firstcall = True return result -tail_recursive = upgrade_dec(TailRecursive) +def tail_recursive(func): + return decorator.apply(TailRecursive, func) + +@tail_recursive +def factorial(n, acc=1): + "The good old factorial" + if n == 0: return acc + return factorial(n-1, n*acc) def fact(n): # this is not tail-recursive if n == 0: return 1 return n * fact(n-1) + +datalist = [] + +def write(data): + "Writing to a sigle-access resource" + with threading.Lock(): + time.sleep(1) + datalist.append(data) + + +if __name__ == '__main__': + import doctest; doctest.testmod() -- cgit v1.2.1 From f368a98c18161cc3eb6f316a1e0dd3228a808925 Mon Sep 17 00:00:00 2001 From: "michele.simionato" Date: Wed, 10 Dec 2008 07:05:52 +0000 Subject: Removed decorator.apply and decorator.wrap --- decorator.py | 38 ++++------ documentation.py | 211 +++++++++++++++++++++++++++++-------------------------- setup.py | 61 ++++++++-------- 3 files changed, 159 insertions(+), 151 deletions(-) diff --git a/decorator.py b/decorator.py index 1f1607b..a04f9e6 100755 --- a/decorator.py +++ b/decorator.py @@ -108,30 +108,22 @@ class FunctionMaker(object): self.update(func, __source__=source) return func -def decorator_wrap(caller, func): - "Decorate a function with a caller" - fun = FunctionMaker(func) - src = """def %(name)s(%(signature)s): +def decorator(caller, func=None): + """ + decorator(caller) converts a caller function into a decorator; + decorator(caller, func) decorates a function using a caller. + """ + if func is None: # returns a decorator + fun = FunctionMaker(caller) + first_arg = inspect.getargspec(caller)[0][0] + src = 'def %s(%s): return _call_(caller, %s)' % ( + caller.__name__, first_arg, first_arg) + return fun.make(src, caller=caller, _call_=decorator) + else: # returns a decorated function + fun = FunctionMaker(func) + src = """def %(name)s(%(signature)s): return _call_(_func_, %(signature)s)""" - return fun.make(src, _func_=func, _call_=caller) - -def decorator_apply(dec, func): - "Decorate a function using a signature-non-preserving decorator" - fun = FunctionMaker(func) - src = '''def %(name)s(%(signature)s): - return decorated(%(signature)s)''' - return fun.make(src, decorated=dec(func)) - -def decorator(caller): - "decorator(caller) converts a caller function into a decorator" - fun = FunctionMaker(caller) - first_arg = fun.signature.split(',')[0] - src = 'def %s(%s): return _call_(caller, %s)' % ( - caller.__name__, first_arg, first_arg) - return fun.make(src, caller=caller, _call_=decorator_wrap) - -decorator.wrap = decorator_wrap -decorator.apply = decorator_apply + return fun.make(src, _func_=func, _call_=caller) ###################### deprecated functionality ######################### diff --git a/documentation.py b/documentation.py index a73693a..be2a3a2 100644 --- a/documentation.py +++ b/documentation.py @@ -4,8 +4,8 @@ The ``decorator`` module :author: Michele Simionato :E-mail: michele.simionato@gmail.com -:version: 3.0 (11 December 2008) -:Download page: http://pypi.python.org/decorator +:version: $VERSION ($DATE) +:Download page: http://pypi.python.org/pypi/decorator :Installation: ``easy_install decorator`` :License: BSD license @@ -88,6 +88,9 @@ A simple implementation for Python 2.5 could be the following: $$memoize25 +Notice that in general it is impossible to memoize correctly something +that depends on non-hashable arguments. + Here we used the ``functools.update_wrapper`` utility, which has been added in Python 2.5 to simplify the definition of decorators. @@ -141,10 +144,18 @@ and implements the tracing capability: $$_memoize -At this point you can define your decorator by means of ``decorator.wrap``: +At this point you can define your decorator by means of ``decorator``: $$memoize +The difference with respect to the Python 2.5 approach, which is based +on nested functions, is that the decorator module forces you to lift +the inner function at the outer level (*flat is better than nested*). +Moreover, you are forced to pass explicitly the function you want to +decorate as first argument of the helper function, also know as +the *caller* function, since it calls the original function with the +given arguments. + Here is a test of usage: >>> @memoize @@ -163,9 +174,6 @@ The signature of ``heavy_computation`` is the one you would expect: >>> print getargspec(heavy_computation) ([], None, None, None) -Notice that in general it is impossible to memoize correctly something -that depends on mutable arguments. - A ``trace`` decorator ------------------------------------------------------ @@ -220,40 +228,35 @@ in Python 2.6 and removed in Python 3.0. ``decorator`` is a decorator --------------------------------------------- -The ``decorator`` module provides an easy shortcut to convert -the helper function into a signature-preserving decorator: the -``decorator`` function itself, which can be considered as a signature-changing +It may be annoying to be forced to write a caller function (like the ``_trace`` +function above) and then a trivial wrapper +(``def trace(f): return decorator(_trace, f)``) every time. For this reason, +the ``decorator`` module provides an easy shortcut to convert +the caller function into a signature-preserving decorator: +you can call ``decorator`` with a single argument and you will get out +your decorator: ``trace = decorator(_trace)``. +That means that the ``decorator`` function can be used as a signature-changing decorator, just as ``classmethod`` and ``staticmethod``. However, ``classmethod`` and ``staticmethod`` return generic objects which are not callable, while ``decorator`` returns signature-preserving decorators, i.e. functions of a single argument. -Therefore, you can write +For instance, you can write directly >>> @decorator -... def tracing(f, *args, **kw): +... def trace(f, *args, **kw): ... print "calling %s with args %s, %s" % (f.func_name, args, kw) ... return f(*args, **kw) -instead of - -.. code-block:: python - - def _tracing(f, *args, **kw): - print "calling %s with args %s, %s" % (f.func_name, args, kw) - return f(*args, **kw) +and now ``trace`` will be a decorator. You +can easily check that the signature has changed: - def tracing(f): - return decorator.wrap(_tracing, f) - -We can easily check that the signature has changed: - ->>> print getargspec(tracing) +>>> print getargspec(trace) (['f'], None, None, None) -Therefore now ``tracing`` can be used as a decorator and +Therefore now ``trace`` can be used as a decorator and the following will work: ->>> @tracing +>>> @trace ... def func(): pass >>> func() @@ -440,18 +443,55 @@ interface requirements for (more stringent) inheritance requirements. .. _I generally dislike inheritance: http://stacktrace.it/articoli/2008/06/i-pericoli-della-programmazione-con-i-mixin1 -Dealing with third party decorators: ``decorator.apply`` ------------------------------------------------------------- +The ``FunctionMaker`` class +--------------------------------------------------------------- + +The public API of the ``decorator`` module consists in the +``decorator`` function and its two attributes ``decorator`` and +``decorator_apply``. Internally, the functionality is implemented via +a ``FunctionMaker`` class which is able to generate on the fly +functions with a given name and signature. You should not need to +resort to ``FunctionMaker`` when writing ordinary decorators, but it +is interesting to know how the module works internally, so I have +decided to add this paragraph. Notice that while I do not have plan +to change or remove the functionality provided in the +``FunctionMaker`` class, I do not guarantee that it will stay +unchanged forever. On the other hand, the functionality provided by +``decorator`` has been there from version 0.1 and it is guaranteed to +stay there forever. +``FunctionMaker`` takes the name and the signature of a function in +input, or a whole function. Here is an example of how to +restrict the signature of a function: + +>>> def f(*args, **kw): +... print args, kw + +>>> f1 = FunctionMaker(name="f1", signature="a,b").make(''' +... def %(name)s(%(signature)s): +... f(%(signature)s)''', f=f) + +>>> f1(1,2) +(1, 2) {} Sometimes you find on the net some cool decorator that you would like to include in your code. However, more often than not the cool decorator is not signature-preserving. Therefore you may want an easy way to upgrade third party decorators to signature-preserving decorators without -having to rewrite them in terms of ``decorator``. To this aim the -``decorator`` module provides an utility function -``decorator.apply(third_party_decorator, func)``. +having to rewrite them in terms of ``decorator``. You can use a +``FunctionMaker`` to implement that functionality as follows: + +$$decorator_apply -In order to give an example of usage, I will show a +Notice that I am not providing this functionality in the ``decorator`` +module directly since I think it is best to rewrite a decorator rather +than adding an additional level of indirection. However, practicality +beats purity, so you can add ``decorator_apply`` to your toolbox and +use it if you need to. + +``tail-recursive`` +------------------------------------------------------------ + +In order to give an example of usage of ``decorator_apply``, I will show a pretty slick decorator that converts a tail-recursive function in an iterative function. I have shamelessly stolen the basic idea from Kay Schluehr's recipe in the Python Cookbook, @@ -530,7 +570,7 @@ a penalty in your specific use case is to measure it. You should be aware that decorators will make your tracebacks longer and more difficult to understand. Consider this example: ->>> @tracing +>>> @trace ... def f(): ... 1/0 @@ -542,13 +582,13 @@ Traceback (most recent call last): File "", line 1, in ? f() File "", line 2, in f - File "", line 4, in tracing + File "", line 4, in trace return f(*args, **kw) File "", line 3, in f 1/0 ZeroDivisionError: integer division or modulo by zero -You see here the inner call to the decorator ``tracing``, which calls +You see here the inner call to the decorator ``trace``, which calls ``f(*args, **kw)``, and a reference to ``File "", line 2, in f``. This latter reference is due to the fact that internally the decorator module uses ``exec`` to generate the decorated function. Notice that @@ -579,7 +619,7 @@ a ``__source__`` attribute to the decorated function, therefore you can get the code which is executed: >>> print f.__source__ -# _call_= +# _call_= # _func_= def f(): return _call_(_func_, ) @@ -610,14 +650,14 @@ callable objects, nor on built-in functions, due to limitations of the Moreover, you can decorate anonymous functions: ->>> tracing(lambda : None)() +>>> trace(lambda : None)() calling with args (), {} There is a restriction on the names of the arguments: for instance, if try to call an argument ``_call_`` or ``_func_`` you will get a ``NameError``: ->>> @tracing +>>> @trace ... def f(_func_): print f ... Traceback (most recent call last): @@ -633,7 +673,7 @@ a copy of the original function attributes: >>> f.attr1 = "something" # setting an attribute >>> f.attr2 = "something else" # setting another attribute ->>> traced_f = tracing(f) # the decorated function +>>> traced_f = trace(f) # the decorated function >>> traced_f.attr1 'something' @@ -641,41 +681,6 @@ a copy of the original function attributes: >>> f.attr2 # the original attribute did not change 'something else' -The ``FunctionMaker`` class ---------------------------------------------------------------- - -The public API of the ``decorator`` module consists in the -``decorator`` function and its two attributes ``decorator.wrap`` and -``decorator.apply``. Internally, the functionality is implemented via -a ``FunctionMaker`` class which is able to generate on the fly -functions with a given name and signature. You should not need to -resort to ``FunctionMaker`` when writing ordinary decorators, but it -is interesting to know how the module works internally, so I have -decided to add this paragraph. Notice that while I do not have plan -to change or remove the functionality provided in the -``FunctionMaker`` class, I do not guarantee that it will stay -unchanged forever. On the other hand, the functionality provided by -``decorator`` has been there from version 0.1 and it is guaranteed to -stay there forever. -``FunctionMaker`` takes the name and the signature of a function in -input, or a whole function. Here is an example of how to -restrict the signature of a function: - ->>> def f(*args, **kw): -... print args, kw - ->>> f1 = FunctionMaker(name="f1", signature="a,b").make(''' -... def %(name)s(%(signature)s): -... f(%(signature)s)''', f=f) - ->>> f1(1,2) -(1, 2) {} - -The utility ``decorator.wrap`` instead takes a function in input and -returns a new function; it is defined as follows: - -$$decorator_wrap - Backward compatibility notes --------------------------------------------------------------- @@ -689,7 +694,7 @@ in the future. For the moment, using them raises a ``DeprecationWarning``. to be changed anyway to work with Python 3.0; ``new_wrapper`` has been removed since it was useless: its major use case (converting signature changing decorators to signature preserving decorators) -has been subsumed by ``decorator.apply`` +has been subsumed by ``decorator_apply`` and the other use case can be managed with the ``FunctionMaker``. Finally ``decorator`` cannot be used as a class decorator and the @@ -737,15 +742,25 @@ you are unhappy with it, send me a patch! from __future__ import with_statement import sys, threading, time, functools from decorator import * +from setup import VERSION + +today = time.strftime('%Y-%m-%d') + +__doc__ = __doc__.replace('$VERSION', VERSION).replace('$DATE', today) -decorator_wrap = decorator.wrap +def decorator_apply(dec, func): + "Decorate a function using a signature-non-preserving decorator" + fun = FunctionMaker(func) + src = '''def %(name)s(%(signature)s): + return decorated(%(signature)s)''' + return fun.make(src, decorated=dec(func)) def _trace(f, *args, **kw): print "calling %s with args %s, %s" % (f.func_name, args, kw) return f(*args, **kw) def trace(f): - return decorator.wrap(_trace, f) + return decorator(_trace, f) def delayed(nsec): def _delayed(proc, *args, **kw): @@ -762,13 +777,28 @@ def identity_dec(func): @identity_dec def example(): pass +def memoize25(func): + func.cache = {} + def memoize(*args, **kw): + if kw: + key = args, frozenset(kw.items()) + else: + key = args + cache = func.cache + if key in cache: + return cache[key] + else: + cache[key] = result = func(*args, **kw) + return result + return functools.update_wrapper(memoize, func) + def _memoize(func, *args, **kw): # args and kw must be hashable if kw: - key = args, frozenset(kw.items()) + key = args, frozenset(kw.items()) else: - key = args - cache = func.cache # created at decoration time + key = args + cache = func.cache if key in cache: return cache[key] else: @@ -777,22 +807,7 @@ def _memoize(func, *args, **kw): def memoize(f): f.cache = {} - return decorator.wrap(_memoize, f) - -def memoize25(func): - func.cache = {} - def memoize(*args, **kw): - if kw: - key = args, frozenset(kw.items()) - else: - key = args - cache = func.cache # created at decoration time - if key in cache: - return cache[key] - else: - cache[key] = result = func(*args, **kw) - return result - return functools.update_wrapper(memoize, func) + return decorator(_memoize, f) threaded = delayed(0) # no-delay decorator @@ -847,7 +862,7 @@ class Restricted(object): '%s does not have the permission to run %s!' % (userclass.__name__, func.__name__)) def __call__(self, func): - return decorator.wrap(self.call, func) + return decorator(self.call, func) class Action(object): @Restricted(User) @@ -894,7 +909,7 @@ class TailRecursive(object): return result def tail_recursive(func): - return decorator.apply(TailRecursive, func) + return decorator_apply(TailRecursive, func) @tail_recursive def factorial(n, acc=1): diff --git a/setup.py b/setup.py index e6240f6..3b18292 100644 --- a/setup.py +++ b/setup.py @@ -3,35 +3,36 @@ try: except ImportError: from distutils.core import setup -setup(name='decorator', - version='2.3.2', - description=\ - 'Better living through Python with decorators.', - long_description="""\ -As of now, writing custom decorators correctly requires some experience -and it is not as easy as it could be. For instance, typical implementations -of decorators involve nested functions, and we all know -that flat is better than nested. Moreover, typical implementations -of decorators do not preserve the signature of decorated functions, -thus confusing both documentation tools and developers. +VERSION = '3.0.0' -The aim of the decorator module it to simplify the usage of decorators -for the average programmer, and to popularize decorators usage giving -examples of useful decorators, such as memoize, tracing, -redirecting_stdout, locked, etc.""", - author='Michele Simionato', - author_email='michele.simionato@gmail.com', - url='http://www.phyast.pitt.edu/~micheles/python/documentation.html', - license="BSD License", - py_modules = ['decorator'], - keywords="decorators generic utility", - classifiers=['Development Status :: 5 - Production/Stable', - 'Intended Audience :: Developers', - 'License :: OSI Approved :: BSD License', - 'Natural Language :: English', - 'Operating System :: OS Independent', - 'Programming Language :: Python', - 'Topic :: Software Development :: Libraries', - 'Topic :: Utilities'], - zip_safe=False) +if __name__ == '__main__': + setup(name='decorator', + version=VERSION, + description='Better living through Python with decorators', + long_description="""\ + As of now, writing custom decorators correctly requires some experience + and it is not as easy as it could be. For instance, typical implementations + of decorators involve nested functions, and we all know + that flat is better than nested. Moreover, typical implementations + of decorators do not preserve the signature of decorated functions, + thus confusing both documentation tools and developers. + + The aim of the decorator module it to simplify the usage of decorators + for the average programmer, and to popularize decorators usage giving + examples of useful decorators, such as memoize, tracing, threaded, etc.""", + author='Michele Simionato', + author_email='michele.simionato@gmail.com', + url='http://pypi.python.org/pypi/decorator', + license="BSD License", + py_modules = ['decorator'], + keywords="decorators generic utility", + classifiers=['Development Status :: 5 - Production/Stable', + 'Intended Audience :: Developers', + 'License :: OSI Approved :: BSD License', + 'Natural Language :: English', + 'Operating System :: OS Independent', + 'Programming Language :: Python', + 'Topic :: Software Development :: Libraries', + 'Topic :: Utilities'], + zip_safe=False) -- cgit v1.2.1 From f1f691a6a455aa49e68f1b55d21d241b848142a4 Mon Sep 17 00:00:00 2001 From: "michele.simionato" Date: Wed, 10 Dec 2008 17:11:39 +0000 Subject: Various fixes on the getsource functionality --- decorator.py | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/decorator.py b/decorator.py index a04f9e6..0253ad6 100755 --- a/decorator.py +++ b/decorator.py @@ -57,7 +57,7 @@ class FunctionMaker(object): self.dict = func.__dict__.copy() if name: self.name = name - if signature: + if signature is not None: self.signature = signature if defaults: self.defaults = defaults @@ -67,7 +67,8 @@ class FunctionMaker(object): self.module = module if funcdict: self.dict = funcdict - self.name, self.signature # check existence required attributes + assert self.name and hasattr(self, 'signature') + # check existence required attributes def update(self, func, **kw): "Update the signature of func with the data in self" @@ -78,9 +79,9 @@ class FunctionMaker(object): func.__module__ = getattr(self, 'module', _callermodule()) func.__dict__.update(kw) - def make(self, templ, save_source=False, **evaldict): + def make(self, src_templ, save_source=False, **evaldict): "Make a new function from a given template and update the signature" - src = templ % vars(self) # expand name and signature + src = src_templ % vars(self) # expand name and signature mo = DEF.match(src) if mo is None: raise SyntaxError('not a valid function template\n%s' % src) -- cgit v1.2.1 From 748b99ff041ec3b890bb96bb8b91d9a2cdc75c1a Mon Sep 17 00:00:00 2001 From: "michele.simionato" Date: Thu, 11 Dec 2008 06:58:37 +0000 Subject: Various improvements to the management of the source code --- decorator.py | 49 ++++++++++++++++++++++++++++---------------- documentation.py | 62 ++++++++++++++++++++++---------------------------------- 2 files changed, 56 insertions(+), 55 deletions(-) diff --git a/decorator.py b/decorator.py index 0253ad6..b2c3304 100755 --- a/decorator.py +++ b/decorator.py @@ -27,14 +27,22 @@ for the documentation. __all__ = ["decorator", "FunctionMaker", "getinfo", "new_wrapper"] -import os, sys, re, inspect, warnings, tempfile +import os, sys, re, inspect, warnings DEF = re.compile('\s*def\s*([_\w][_\w\d]*)\s*\(') -# helper -def _callermodule(level=2): - return sys._getframe(level).f_globals.get('__name__', '?') +# patch inspect.getsource to recognize the __source__ attribute +inspect_getsource = inspect.getsource +def getsource(obj): + "A replacement for inspect.getsource honoring the __source__ attribute" + try: + return obj.__source__ + except AttributeError: + return inspect_getsource(obj) + +inspect.getsource = getsource + # basic functionality class FunctionMaker(object): """ @@ -67,8 +75,8 @@ class FunctionMaker(object): self.module = module if funcdict: self.dict = funcdict - assert self.name and hasattr(self, 'signature') # check existence required attributes + assert self.name and hasattr(self, 'signature') def update(self, func, **kw): "Update the signature of func with the data in self" @@ -76,10 +84,11 @@ class FunctionMaker(object): func.__doc__ = getattr(self, 'doc', None) func.__dict__ = getattr(self, 'dict', {}) func.func_defaults = getattr(self, 'defaults', None) - func.__module__ = getattr(self, 'module', _callermodule()) + callermodule = sys._getframe(3).f_globals.get('__name__', '?') + func.__module__ = getattr(self, 'module', callermodule) func.__dict__.update(kw) - def make(self, src_templ, save_source=False, **evaldict): + def make(self, src_templ, **evaldict): "Make a new function from a given template and update the signature" src = src_templ % vars(self) # expand name and signature mo = DEF.match(src) @@ -89,22 +98,26 @@ class FunctionMaker(object): reserved_names = set([name] + [ arg.strip(' *') for arg in self.signature.split(',')]) s = '' - for n, v in evaldict.items(): + for n, v in evaldict.iteritems(): if inspect.isfunction(v): s += '# %s=\n' % (n, v.__module__, v.__name__) + elif isinstance(v, basestring): + s += '# %s=\n%s\n' % (name, '\n'.join( + '## ' + line for line in v.splitlines())) + else: + s += '# %s=%r\n' % (n, v) if n in reserved_names: raise NameError('%s is overridden in\n%s' % (n, src)) source = s + src if not source.endswith('\n'): # add a newline just for safety source += '\n' - if save_source: - fhandle, fname = tempfile.mkstemp() - os.write(fhandle, source) - os.close(fhandle) - else: - fname = '?' - code = compile(source, fname, 'single') - exec code in evaldict + try: + code = compile(source, '', 'single') + exec code in evaldict + except: + print >> sys.stderr, 'Error in generated code:' + print >> sys.stderr, source + raise func = evaldict[name] self.update(func, __source__=source) return func @@ -124,7 +137,9 @@ def decorator(caller, func=None): fun = FunctionMaker(func) src = """def %(name)s(%(signature)s): return _call_(_func_, %(signature)s)""" - return fun.make(src, _func_=func, _call_=caller) + decorated = fun.make(src, _func_=func, _call_=caller) + decorated.__source__ = inspect_getsource(func) + return decorated ###################### deprecated functionality ######################### diff --git a/documentation.py b/documentation.py index be2a3a2..6e92c22 100644 --- a/documentation.py +++ b/documentation.py @@ -265,7 +265,7 @@ calling func with args (), {} For the rest of this document, I will discuss examples of useful decorators built on top of ``decorator``. -``delayed`` and ``threaded`` +``delayed`` and ``async`` -------------------------------------------- Often, one wants to define families of decorators, i.e. decorators depending @@ -306,40 +306,34 @@ to deserve a name: .. code-block:: python - threaded = delayed(0) + async = delayed(0, name='async') # no-delay decorator -Threaded procedures will be executed in a separated thread as soon -as they are called. Here is an example. +Asynchronous procedures will be executed in a parallel thread. Suppose one wants to write some data to an external resource which can be accessed by a single user at once (for instance a printer). Then the access to the writing function must -be locked: +be locked. Here is a minimalistic example: -.. code-block:: python - - import time - - datalist = [] # for simplicity the written data are stored into a list. - -$$write - -Since the writing function is locked, we are guaranteed that at any given time -there is at most one writer. Here is an example. +>>> datalist = [] # for simplicity the written data are stored into a list. ->>> @threaded -... def writedata(data): -... write(data) +>>> @async +... def write(data): +... # append data to the datalist by locking +... with threading.Lock(): +... time.sleep(1) # emulate some long running operation +... datalist.append(data) +... # other operations not requiring a lock here -Each call to ``writedata`` will create a new writer thread, but there will +Each call to ``write`` will create a new writer thread, but there will be no synchronization problems since ``write`` is locked. ->>> writedata("data1") +>>> write("data1") <_Timer(Thread-1, started)> >>> time.sleep(.1) # wait a bit, so we are sure data2 is written after data1 ->>> writedata("data2") +>>> write("data2") <_Timer(Thread-2, started)> >>> time.sleep(2) # wait for the writers to complete @@ -756,18 +750,21 @@ def decorator_apply(dec, func): return fun.make(src, decorated=dec(func)) def _trace(f, *args, **kw): - print "calling %s with args %s, %s" % (f.func_name, args, kw) + print "calling %s with args %s, %s" % (f.__name__, args, kw) return f(*args, **kw) def trace(f): return decorator(_trace, f) -def delayed(nsec): - def _delayed(proc, *args, **kw): +def delayed(nsec, name='delayed'): + def caller(proc, *args, **kw): thread = threading.Timer(nsec, proc, args, kw) thread.start() return thread - return decorator(_delayed) + caller.__name__ = name + return decorator(caller) + +async = delayed(0, name='async') # no-delay decorator def identity_dec(func): def wrapper(*args, **kw): @@ -781,7 +778,7 @@ def memoize25(func): func.cache = {} def memoize(*args, **kw): if kw: - key = args, frozenset(kw.items()) + key = args, frozenset(kw.iteritems()) else: key = args cache = func.cache @@ -795,7 +792,7 @@ def memoize25(func): def _memoize(func, *args, **kw): # args and kw must be hashable if kw: - key = args, frozenset(kw.items()) + key = args, frozenset(kw.iteritems()) else: key = args cache = func.cache @@ -809,8 +806,6 @@ def memoize(f): f.cache = {} return decorator(_memoize, f) -threaded = delayed(0) # no-delay decorator - def blocking(not_avail="Not Available"): def _blocking(f, *args, **kw): if not hasattr(f, "thread"): # no thread running @@ -921,14 +916,5 @@ def fact(n): # this is not tail-recursive if n == 0: return 1 return n * fact(n-1) -datalist = [] - -def write(data): - "Writing to a sigle-access resource" - with threading.Lock(): - time.sleep(1) - datalist.append(data) - - if __name__ == '__main__': import doctest; doctest.testmod() -- cgit v1.2.1 From e8ebd10028020ff8f864aa8dcf2855693e593b30 Mon Sep 17 00:00:00 2001 From: "michele.simionato" Date: Fri, 12 Dec 2008 10:14:49 +0000 Subject: Changed the documentation of the decorator module and improved the source code management --- decorator.py | 45 +++------ documentation.py | 271 +++++++++++++++++++++++++++++-------------------------- 2 files changed, 155 insertions(+), 161 deletions(-) diff --git a/decorator.py b/decorator.py index b2c3304..943f8f2 100755 --- a/decorator.py +++ b/decorator.py @@ -25,24 +25,12 @@ Decorator module, see http://pypi.python.org/pypi/decorator for the documentation. """ -__all__ = ["decorator", "FunctionMaker", "getinfo", "new_wrapper"] +__all__ = ["decorator", "FunctionMaker", "deprecated", "getinfo", "new_wrapper"] import os, sys, re, inspect, warnings DEF = re.compile('\s*def\s*([_\w][_\w\d]*)\s*\(') -# patch inspect.getsource to recognize the __source__ attribute -inspect_getsource = inspect.getsource - -def getsource(obj): - "A replacement for inspect.getsource honoring the __source__ attribute" - try: - return obj.__source__ - except AttributeError: - return inspect_getsource(obj) - -inspect.getsource = getsource - # basic functionality class FunctionMaker(object): """ @@ -88,38 +76,32 @@ class FunctionMaker(object): func.__module__ = getattr(self, 'module', callermodule) func.__dict__.update(kw) - def make(self, src_templ, **evaldict): + def make(self, src_templ, evaldict=None, addsource=None, **attrs): "Make a new function from a given template and update the signature" src = src_templ % vars(self) # expand name and signature + evaldict = evaldict or {} mo = DEF.match(src) if mo is None: raise SyntaxError('not a valid function template\n%s' % src) name = mo.group(1) # extract the function name reserved_names = set([name] + [ arg.strip(' *') for arg in self.signature.split(',')]) - s = '' for n, v in evaldict.iteritems(): - if inspect.isfunction(v): - s += '# %s=\n' % (n, v.__module__, v.__name__) - elif isinstance(v, basestring): - s += '# %s=\n%s\n' % (name, '\n'.join( - '## ' + line for line in v.splitlines())) - else: - s += '# %s=%r\n' % (n, v) if n in reserved_names: raise NameError('%s is overridden in\n%s' % (n, src)) - source = s + src - if not source.endswith('\n'): # add a newline just for safety - source += '\n' + if not src.endswith('\n'): # add a newline just for safety + src += '\n' try: - code = compile(source, '', 'single') + code = compile(src, '', 'single') exec code in evaldict except: print >> sys.stderr, 'Error in generated code:' - print >> sys.stderr, source + print >> sys.stderr, src raise func = evaldict[name] - self.update(func, __source__=source) + if addsource: + attrs['__source__'] = src + addsource + self.update(func, **attrs) return func def decorator(caller, func=None): @@ -132,14 +114,13 @@ def decorator(caller, func=None): first_arg = inspect.getargspec(caller)[0][0] src = 'def %s(%s): return _call_(caller, %s)' % ( caller.__name__, first_arg, first_arg) - return fun.make(src, caller=caller, _call_=decorator) + return fun.make(src, dict(caller=caller, _call_=decorator), + undecorated=caller) else: # returns a decorated function fun = FunctionMaker(func) src = """def %(name)s(%(signature)s): return _call_(_func_, %(signature)s)""" - decorated = fun.make(src, _func_=func, _call_=caller) - decorated.__source__ = inspect_getsource(func) - return decorated + return fun.make(src, dict(_func_=func, _call_=caller), undecorated=func) ###################### deprecated functionality ######################### diff --git a/documentation.py b/documentation.py index 6e92c22..10879aa 100644 --- a/documentation.py +++ b/documentation.py @@ -5,6 +5,7 @@ The ``decorator`` module :author: Michele Simionato :E-mail: michele.simionato@gmail.com :version: $VERSION ($DATE) +:Requirements: Python 2.4+ :Download page: http://pypi.python.org/pypi/decorator :Installation: ``easy_install decorator`` :License: BSD license @@ -184,10 +185,12 @@ $$_trace $$trace Then, you can write the following: + +.. code-block:: python ->>> @trace -... def f1(x): -... pass + >>> @trace + ... def f1(x): + ... pass It is immediate to verify that ``f1`` works @@ -201,26 +204,30 @@ and it that it has the correct signature: The same decorator works with functions of any signature: ->>> @trace -... def f(x, y=1, z=2, *args, **kw): -... pass - ->>> f(0, 3) -calling f with args (0, 3, 2), {} +.. code-block:: python + + >>> @trace + ... def f(x, y=1, z=2, *args, **kw): + ... pass ->>> print getargspec(f) -(['x', 'y', 'z'], 'args', 'kw', (1, 2)) + >>> f(0, 3) + calling f with args (0, 3, 2), {} + + >>> print getargspec(f) + (['x', 'y', 'z'], 'args', 'kw', (1, 2)) That includes even functions with exotic signatures like the following: ->>> @trace -... def exotic_signature((x, y)=(1,2)): return x+y - ->>> print getargspec(exotic_signature) -([['x', 'y']], None, None, ((1, 2),)) ->>> exotic_signature() -calling exotic_signature with args ((1, 2),), {} -3 +.. code-block:: python + + >>> @trace + ... def exotic_signature((x, y)=(1,2)): return x+y + + >>> print getargspec(exotic_signature) + ([['x', 'y']], None, None, ((1, 2),)) + >>> exotic_signature() + calling exotic_signature with args ((1, 2),), {} + 3 Notice that the support for exotic signatures has been deprecated in Python 2.6 and removed in Python 3.0. @@ -265,52 +272,24 @@ calling func with args (), {} For the rest of this document, I will discuss examples of useful decorators built on top of ``decorator``. -``delayed`` and ``async`` +``async`` -------------------------------------------- -Often, one wants to define families of decorators, i.e. decorators depending -on one or more parameters. - -Here I will consider the example of a one-parameter family of ``delayed`` -decorators taking a procedure and converting it into a delayed procedure. -In this case the time delay is the parameter. +Here I show a decorator +which is able to convert a blocking procedure into an asynchronous +procedure. The procedure, when called, +is executed in a separate thread. The implementation is not difficult: -A delayed procedure is a procedure that, when called, -is executed in a separate thread after a certain time -delay. The implementation is not difficult: +$$_async +$$async -$$delayed - -Notice that without the help of ``decorator``, an additional level of -nesting would have been needed. - -Delayed decorators as intended to be used on procedures, i.e. +``async`` as intended to be used on procedures, i.e. on functions returning ``None``, since the return value of the original function is discarded by this implementation. The decorated function returns the current execution thread, which can be stored and checked later, for instance to verify that the thread ``.isAlive()``. -Delayed procedures can be useful in many situations. For instance, I have used -this pattern to start a web browser *after* the web server started, -in code such as - ->>> @delayed(2) -... def start_browser(): -... "code to open an external browser window here" - ->>> #start_browser() # will open the browser in 2 seconds ->>> #server.serve_forever() # enter the server mainloop - -The particular case in which there is no delay is important enough -to deserve a name: - -.. code-block:: python - - async = delayed(0, name='async') # no-delay decorator - -Asynchronous procedures will be executed in a parallel thread. - -Suppose one wants to write some data to +Here is an example of usage. Suppose one wants to write some data to an external resource which can be accessed by a single user at once (for instance a printer). Then the access to the writing function must be locked. Here is a minimalistic example: @@ -329,12 +308,12 @@ Each call to ``write`` will create a new writer thread, but there will be no synchronization problems since ``write`` is locked. >>> write("data1") -<_Timer(Thread-1, started)> + >>> time.sleep(.1) # wait a bit, so we are sure data2 is written after data1 >>> write("data2") -<_Timer(Thread-2, started)> + >>> time.sleep(2) # wait for the writers to complete @@ -349,36 +328,43 @@ sometimes it is best to have back a "busy" message than to block everything. This behavior can be implemented with a suitable decorator: $$blocking + +(notice that without the help of ``decorator``, an additional level of +nesting would have been needed). This is actually an example +of a one-parameter family of decorators where the +"busy message" is the parameter. Functions decorated with ``blocking`` will return a busy message if the resource is unavailable, and the intended result if the resource is available. For instance: ->>> @blocking("Please wait ...") -... def read_data(): -... time.sleep(3) # simulate a blocking resource -... return "some data" +.. code-block:: python + + >>> @blocking("Please wait ...") + ... def read_data(): + ... time.sleep(3) # simulate a blocking resource + ... return "some data" ->>> print read_data() # data is not available yet -Please wait ... + >>> print read_data() # data is not available yet + Please wait ... ->>> time.sleep(1) ->>> print read_data() # data is not available yet -Please wait ... + >>> time.sleep(1) + >>> print read_data() # data is not available yet + Please wait ... ->>> time.sleep(1) ->>> print read_data() # data is not available yet -Please wait ... + >>> time.sleep(1) + >>> print read_data() # data is not available yet + Please wait ... ->>> time.sleep(1.1) # after 3.1 seconds, data is available ->>> print read_data() -some data + >>> time.sleep(1.1) # after 3.1 seconds, data is available + >>> print read_data() + some data decorator factories -------------------------------------------------------------------- -We have already seen examples -of simple decorator factories, implemented as functions returning a +We have just seen an example +of a simple decorator factories, implemented as a function returning a decorator. For more complex situations, it is more convenient to implement decorator factories as classes returning callable objects that can be used as signature-preserving decorators. @@ -457,15 +443,17 @@ stay there forever. input, or a whole function. Here is an example of how to restrict the signature of a function: ->>> def f(*args, **kw): -... print args, kw +.. code-block:: python ->>> f1 = FunctionMaker(name="f1", signature="a,b").make(''' -... def %(name)s(%(signature)s): -... f(%(signature)s)''', f=f) + >>> def f(*args, **kw): + ... print args, kw ->>> f1(1,2) -(1, 2) {} + >>> f1 = FunctionMaker(name="f1", signature="a,b").make(''' + ... def %(name)s(%(signature)s): + ... f(%(signature)s)''', dict(f=f)) + + >>> f1(1,2) + (1, 2) {} Sometimes you find on the net some cool decorator that you would like to include in your code. However, more often than not the cool @@ -523,6 +511,55 @@ $$fact making a recursive call, or returns directly the result of a recursive call). +Getting the source code +--------------------------------------------------- + +Iinternally the decorator module uses ``exec`` to generate the decorated +function with the right signature. Therefore the ordinary +``inspect.getsource`` will not work for decorated +functions. This means that the usual '??' trick in IPython will give you +the (right on the spot) message +``Dynamically generated function. No source code available.``. +In the past I have considered this acceptable, since ``inspect.getsource`` +does not really work even with regular decorators. In that case +``inspect.getsource`` gives you the wrapper source code which is probably +not what you want: + +$$identity_dec +$$example + +>>> import inspect +>>> print inspect.getsource(example) + def wrapper(*args, **kw): + return func(*args, **kw) + + +(see bug report 1764286_ for an explanation of what is happening). +Unfortunately the bug is still there, even in Python 2.6 and 3.0. +There is however a workaround. The decorator module adds an +attribute ``.undecorated`` to the decorated function, containing +a reference to the original function. The easy way to get +the source code is to call ``inspect.getsource`` on the +undecorated function: + +>>> print inspect.getsource(factorial.undecorated) +@tail_recursive +def factorial(n, acc=1): + "The good old factorial" + if n == 0: return acc + return factorial(n-1, n*acc) + + +.. _1764286: http://bugs.python.org/issue1764286 + +Starting from release 3.0, the decorator module also adds +a ``__source__`` attribute to the decorated function. + +The generated function is a closure depending on the the caller +``_call_`` and the original function ``_func_``. For debugging convenience +you get the names of the moduled where they are defined in a comment: +in this example they are defined in the ``__main__`` module. + Caveats and limitations ------------------------------------------- @@ -590,42 +627,6 @@ module uses ``exec`` to generate the decorated function. Notice that called *only once* at function decoration time, and not every time the decorated function is called. -Using ``exec`` means that ``inspect.getsource`` will not work for decorated -functions. This means that the usual '??' trick in IPython will give you -the (right on the spot) message -``Dynamically generated function. No source code available.``. This -however is preferable to the situation with regular decorators, where -``inspect.getsource`` gives you the wrapper source code which is probably -not what you want: - -$$identity_dec -$$example - ->>> import inspect ->>> print inspect.getsource(example) - def wrapper(*args, **kw): - return func(*args, **kw) - - -(see bug report 1764286_ for an explanation of what is happening). -Actually, starting from release 3.0, the decorator module, adds -a ``__source__`` attribute to the decorated function, therefore -you can get the code which is executed: - ->>> print f.__source__ -# _call_= -# _func_= -def f(): - return _call_(_func_, ) - - -.. _1764286: http://bugs.python.org/issue1764286 - -The generated function is a closure depending on the the caller -``_call_`` and the original function ``_func_``. For debugging convenience -you get the names of the moduled where they are defined in a comment: -in this example they are defined in the ``__main__`` module. - At present, there is no clean way to avoid ``exec``. A clean solution would require to change the CPython implementation of functions and add an hook to make it possible to change their signature directly. @@ -702,6 +703,17 @@ downgrade to the 2.3 version. .. _functionality introduced in version 2.3: http://www.phyast.pitt.edu/~micheles/python/documentation.html#class-decorators-and-decorator-factories +Python 3.0 support +------------------------------------------------------------ + +The examples shown here have been tested with Python 2.5. Python 2.4 +is also supported - of course the examples requiring the ``with`` +statement will not work there - as well as Python 2.5. Python 3.0 +is supported too. Simply run the script ``2to3`` on the module +``decorator.py`` and you will get a version of the code running +with Python 3.0. Notice however that the decorator module is little +tested with Python 3.0, since I mostly use Python 2.5. + LICENCE --------------------------------------------- @@ -734,7 +746,7 @@ note, just to gratify my ego. On the other hand, if you use this software and you are unhappy with it, send me a patch! """ from __future__ import with_statement -import sys, threading, time, functools +import sys, threading, time, functools, inspect, itertools from decorator import * from setup import VERSION @@ -747,7 +759,7 @@ def decorator_apply(dec, func): fun = FunctionMaker(func) src = '''def %(name)s(%(signature)s): return decorated(%(signature)s)''' - return fun.make(src, decorated=dec(func)) + return fun.make(src, dict(decorated=dec(func)), undecorated=func) def _trace(f, *args, **kw): print "calling %s with args %s, %s" % (f.__name__, args, kw) @@ -756,16 +768,17 @@ def _trace(f, *args, **kw): def trace(f): return decorator(_trace, f) -def delayed(nsec, name='delayed'): - def caller(proc, *args, **kw): - thread = threading.Timer(nsec, proc, args, kw) - thread.start() - return thread - caller.__name__ = name - return decorator(caller) - -async = delayed(0, name='async') # no-delay decorator +def _async(proc, *args, **kw): + name = '%s-%s' % (proc.__name__, proc.counter.next()) + thread = threading.Thread(None, proc, name, args, kw) + thread.start() + return thread +def async(proc): + # every decorated procedure has its own independent thread counter + proc.counter = itertools.count(1) + return decorator(_async, proc) + def identity_dec(func): def wrapper(*args, **kw): return func(*args, **kw) -- cgit v1.2.1 From e422ac2ebb8a038babc2fb41ab1a8c5aba374be0 Mon Sep 17 00:00:00 2001 From: "michele.simionato" Date: Sun, 14 Dec 2008 06:13:49 +0000 Subject: Published version of decorator 3.0 --- CHANGES.txt | 5 + MANIFEST.in | 1 + Makefile | 19 +- README.txt | 14 +- corner-cases.txt | 40 ---- decorator.py | 4 +- documentation.py | 718 ++++++++++++++++++++++++++++++------------------------- other.txt | 125 ---------- setup.py | 21 +- util.py | 14 -- 10 files changed, 421 insertions(+), 540 deletions(-) create mode 100644 MANIFEST.in mode change 100755 => 100644 Makefile delete mode 100755 corner-cases.txt delete mode 100755 other.txt delete mode 100755 util.py diff --git a/CHANGES.txt b/CHANGES.txt index 5b77483..852ca8b 100755 --- a/CHANGES.txt +++ b/CHANGES.txt @@ -1,6 +1,11 @@ HISTORY ---------- +3.0. New major version introducing ``FunctionMaker`` and the two-argument + syntax for ``decorator``. Moreover, added support for getting the + source code. This version is Python 3.0 ready. + Major overhaul of the documentation, now hosted on + http://packages.python.org/decorator (14/12/2008). 2.3.2. Small optimization in the code for decorator factories. First version with the code uploaded to PyPI (01/12/2008) 2.3.1. Set the zipsafe flag to False, since I want my users to have the source, not diff --git a/MANIFEST.in b/MANIFEST.in new file mode 100644 index 0000000..4ef4f14 --- /dev/null +++ b/MANIFEST.in @@ -0,0 +1 @@ +include documentation.pdf diff --git a/Makefile b/Makefile old mode 100755 new mode 100644 index 738bc81..52405ac --- a/Makefile +++ b/Makefile @@ -1,15 +1,6 @@ -T = /home/micheles/trunk/ROnline/RCommon/Python/ms/tools -V = 2.3.2 +RST=/home/micheles/trunk/ROnline/RCommon/Python/ms/tools/rst.py -documentation.html: documentation.txt - python $T/rst.py documentation -documentation.pdf: documentation.txt - python $T/rst.py -tp documentation -pdf: documentation.pdf - evince documentation.pdf& -decorator-$V.zip: README.txt documentation.txt documentation.html documentation.pdf \ -doctester.py decorator.py setup.py CHANGES.txt performance.sh - zip decorator-$V.zip README.txt documentation.txt documentation.html \ -documentation.pdf decorator.py setup.py doctester.py CHANGES.txt performance.sh -upload: decorator-$V.zip - scp decorator-$V.zip documentation.html alpha.phyast.pitt.edu:public_html/python +pdf: /tmp/documentation.rst + $(RST) -ptd /tmp/documentation.rst; mv /tmp/documentation.pdf . +upload: documentation.pdf + python setup.py register sdist upload diff --git a/README.txt b/README.txt index 859f89c..b78c600 100755 --- a/README.txt +++ b/README.txt @@ -7,16 +7,14 @@ The decorator module requires Python 2.4. Installation: -Unzip the archive in a directory called "decorator" in your Python path. -For instance, on Unices you could give something like that: - -$ unzip decorator.zip -d decorator +Copy the file decorator.py somewhere in your Python path. Testing: -Just go in the package directory and give +Run -$ python doctester.py documentation.txt +$ python documentation.py -This will generate the main.py file containing all the examples -discussed in the documentation, and will run the corresponding tests. +This should work perfectly with Python 2.4 and Python 2.5 and give +minor errors with Python 2.6 (some inner details such as the +introduction of the ArgSpec namedtuple and Thread.__repr__ changed). diff --git a/corner-cases.txt b/corner-cases.txt deleted file mode 100755 index 510addc..0000000 --- a/corner-cases.txt +++ /dev/null @@ -1,40 +0,0 @@ ->>> from decorator import decorator ->>> @decorator -... def identity_dec(f, *a, **k): return f(*a, **k) -... ->>> #defarg=1 ->>> @identity_dec -... def f(f=1): print f -... ->>> f() -1 - ->>> @identity_dec -... def f(_call_): print f -... -Traceback (most recent call last): - ... -AssertionError: You cannot use _call_ or _func_ as argument names! - ->>> @identity_dec -... def f(**_func_): print f -... -Traceback (most recent call last): - ... -AssertionError: You cannot use _call_ or _func_ as argument names! - ->>> @identity_dec -... def f(name): print name -... - ->>> f("z") -z - -The decorator module also works for exotic signatures: - ->>> @identity_dec -... def f((a, (x, (y, z), w)), b): -... print a, b, x, y, z, w - ->>> f([1, [2, [3, 4], 5]], 6) -1 6 2 3 4 5 diff --git a/decorator.py b/decorator.py index 943f8f2..ea38aeb 100755 --- a/decorator.py +++ b/decorator.py @@ -76,7 +76,7 @@ class FunctionMaker(object): func.__module__ = getattr(self, 'module', callermodule) func.__dict__.update(kw) - def make(self, src_templ, evaldict=None, addsource=None, **attrs): + def make(self, src_templ, evaldict=None, addsource=False, **attrs): "Make a new function from a given template and update the signature" src = src_templ % vars(self) # expand name and signature evaldict = evaldict or {} @@ -100,7 +100,7 @@ class FunctionMaker(object): raise func = evaldict[name] if addsource: - attrs['__source__'] = src + addsource + attrs['__source__'] = src self.update(func, **attrs) return func diff --git a/documentation.py b/documentation.py index 10879aa..cdc0685 100644 --- a/documentation.py +++ b/documentation.py @@ -1,11 +1,11 @@ -"""\ +r""" The ``decorator`` module ============================================================= -:author: Michele Simionato +:Author: Michele Simionato :E-mail: michele.simionato@gmail.com -:version: $VERSION ($DATE) -:Requirements: Python 2.4+ +:Version: $VERSION ($DATE) +:Requires: Python 2.4+ :Download page: http://pypi.python.org/pypi/decorator :Installation: ``easy_install decorator`` :License: BSD license @@ -18,7 +18,7 @@ Introduction Python decorators are an interesting example of why syntactic sugar matters. In principle, their introduction in Python 2.4 changed nothing, since they do not provide any new functionality which was not -already present in the language; in practice, their introduction has +already present in the language. In practice, their introduction has significantly changed the way we structure our programs in Python. I believe the change is for the best, and that decorators are a great idea since: @@ -26,22 +26,22 @@ idea since: * decorators help reducing boilerplate code; * decorators help separation of concerns; * decorators enhance readability and maintenability; -* decorators are very explicit. +* decorators are explicit. Still, as of now, writing custom decorators correctly requires some experience and it is not as easy as it could be. For instance, typical implementations of decorators involve nested functions, and we all know that flat is better than nested. -The aim of the ``decorator`` module it to simplify the usage of -decorators for the average programmer, and to popularize decorators -usage giving examples of useful decorators, such as ``memoize``, -``tracing``, etc. +The aim of the ``decorator`` module it to simplify the usage of +decorators for the average programmer, and to popularize decorators by +showing various non-trivial examples. Of course, as all techniques, +decorators can be abused (I have seen that) and you should not try to +solve every problem with a decorator, just because you can. -The core of this module is a decorator factory called ``decorator``. -All decorators discussed here are built as simple recipes on top -of ``decorator``. You may find their source code in the ``documentation.py`` -file. If you execute it, all the examples contained will be doctested. +You may find the source code for all the examples +discussed here in the ``documentation.py`` file, which contains +this documentation in the form of doctests. Definitions ------------------------------------ @@ -49,7 +49,7 @@ Definitions Technically speaking, any Python object which can be called with one argument can be used as a decorator. However, this definition is somewhat too large to be really useful. It is more convenient to split the generic class of -decorators in two groups: +decorators in two subclasses: + *signature-preserving* decorators, i.e. callable objects taking a function as input and returning a function *with the same @@ -66,9 +66,7 @@ are not functions, nor callables. However, signature-preserving decorators are more common and easier to reason about; in particular signature-preserving decorators can be -composed together whereas other -decorators in general cannot (for instance you cannot -meaningfully compose a staticmethod with a classmethod or viceversa). +composed together whereas other decorators in general cannot. Writing signature-preserving decorators from scratch is not that obvious, especially if one wants to define proper decorators that @@ -78,22 +76,26 @@ the issue. Statement of the problem ------------------------------ -A typical decorator is a decorator to memoize functions. -Such a decorator works by caching -the result of a function call in a dictionary, so that the next time +A very common use case for decorators is the memoization of functions. +A ``memoize`` decorator works by caching +the result of the function call in a dictionary, so that the next time the function is called with the same input parameters the result is retrieved from the cache and not recomputed. There are many implementations of ``memoize`` in http://www.python.org/moin/PythonDecoratorLibrary, but they do not preserve the signature. -A simple implementation for Python 2.5 could be the following: +A simple implementation for Python 2.5 could be the following (notice +that in general it is impossible to memoize correctly something +that depends on non-hashable arguments): $$memoize25 -Notice that in general it is impossible to memoize correctly something -that depends on non-hashable arguments. +Here we used the functools.update_wrapper_ utility, which has +been added in Python 2.5 expressly to simplify the definition of decorators +(in older versions of Python you need to copy the function attributes +``__name__``, ``__doc__``, ``__module__`` and ``__dict__`` +from the original function to the decorated function by hand). -Here we used the ``functools.update_wrapper`` utility, which has -been added in Python 2.5 to simplify the definition of decorators. +.. _functools.update_wrapper: http://www.python.org/doc/2.5.2/lib/module-functools.html The implementation above works in the sense that the decorator can accept functions with generic signatures; unfortunately this @@ -103,18 +105,22 @@ general ``memoize25`` returns a function with a Consider for instance the following case: ->>> @memoize25 -... def f1(x): -... time.sleep(1) -... return x +.. code-block:: python + + >>> @memoize25 + ... def f1(x): + ... time.sleep(1) # simulate some long computation + ... return x Here the original function takes a single argument named ``x``, but the decorated function takes any number of arguments and keyword arguments: ->>> from inspect import getargspec ->>> print getargspec(f1) -([], 'args', 'kw', None) +.. code-block:: python + + >>> from inspect import getargspec + >>> print getargspec(f1) + ([], 'args', 'kw', None) This means that introspection tools such as pydoc will give wrong informations about the signature of ``f1``. This is pretty bad: @@ -122,30 +128,35 @@ pydoc will tell you that the function accepts a generic signature ``*args``, ``**kw``, but when you try to call the function with more than an argument, you will get an error: ->>> f1(0, 1) -Traceback (most recent call last): - ... -TypeError: f1() takes exactly 1 argument (2 given) +.. code-block:: python + + >>> f1(0, 1) + Traceback (most recent call last): + ... + TypeError: f1() takes exactly 1 argument (2 given) The solution ----------------------------------------- The solution is to provide a generic factory of generators, which hides the complexity of making signature-preserving decorators -from the application programmer. The ``decorator`` factory -allows to define decorators without the need to use nested functions -or classes. -First of all, you must import ``decorator``: +from the application programmer. The ``decorator`` function in +the ``decorator`` module is such a factory: ->>> from decorator import decorator +.. code-block:: python + + >>> from decorator import decorator -Then you must define a helper function with signature ``(f, *args, **kw)`` -which calls the original function ``f`` with arguments ``args`` and ``kw`` -and implements the tracing capability: +``decorator`` takes two arguments, a caller function describing the +functionality of the decorator and a function to be decorated; it +returns the decorated function. The caller function must have +signature ``(f, *args, **kw)`` and it must call the original function ``f`` +with arguments ``args`` and ``kw``, implementing the wanted capability, +i.e. memoization in this case: $$_memoize -At this point you can define your decorator by means of ``decorator``: +At this point you can define your decorator as follows: $$memoize @@ -153,38 +164,42 @@ The difference with respect to the Python 2.5 approach, which is based on nested functions, is that the decorator module forces you to lift the inner function at the outer level (*flat is better than nested*). Moreover, you are forced to pass explicitly the function you want to -decorate as first argument of the helper function, also know as -the *caller* function, since it calls the original function with the -given arguments. +decorate to the caller function. Here is a test of usage: ->>> @memoize -... def heavy_computation(): -... time.sleep(2) -... return "done" +.. code-block:: python + + >>> @memoize + ... def heavy_computation(): + ... time.sleep(2) + ... return "done" ->>> print heavy_computation() # the first time it will take 2 seconds -done + >>> print heavy_computation() # the first time it will take 2 seconds + done ->>> print heavy_computation() # the second time it will be instantaneous -done + >>> print heavy_computation() # the second time it will be instantaneous + done The signature of ``heavy_computation`` is the one you would expect: ->>> print getargspec(heavy_computation) -([], None, None, None) +.. code-block:: python + + >>> print getargspec(heavy_computation) + ([], None, None, None) A ``trace`` decorator ------------------------------------------------------ -As an additional example, here is how you can define a ``trace`` decorator. +As an additional example, here is how you can define a trivial +``trace`` decorator, which prints a message everytime the traced +function is called: $$_trace $$trace -Then, you can write the following: +Here is an example of usage: .. code-block:: python @@ -194,13 +209,17 @@ Then, you can write the following: It is immediate to verify that ``f1`` works ->>> f1(0) -calling f1 with args (0,), {} +.. code-block:: python + + >>> f1(0) + calling f1 with args (0,), {} and it that it has the correct signature: ->>> print getargspec(f1) -(['x'], None, None, None) +.. code-block:: python + + >>> print getargspec(f1) + (['x'], None, None, None) The same decorator works with functions of any signature: @@ -235,91 +254,49 @@ in Python 2.6 and removed in Python 3.0. ``decorator`` is a decorator --------------------------------------------- -It may be annoying to be forced to write a caller function (like the ``_trace`` +It may be annoying to write a caller function (like the ``_trace`` function above) and then a trivial wrapper (``def trace(f): return decorator(_trace, f)``) every time. For this reason, the ``decorator`` module provides an easy shortcut to convert the caller function into a signature-preserving decorator: -you can call ``decorator`` with a single argument and you will get out -your decorator: ``trace = decorator(_trace)``. -That means that the ``decorator`` function can be used as a signature-changing +you can just call ``decorator`` with a single argument. +In our example you can just write ``trace = decorator(_trace)``. +The ``decorator`` function can also be used as a signature-changing decorator, just as ``classmethod`` and ``staticmethod``. However, ``classmethod`` and ``staticmethod`` return generic objects which are not callable, while ``decorator`` returns signature-preserving decorators, i.e. functions of a single argument. For instance, you can write directly ->>> @decorator -... def trace(f, *args, **kw): -... print "calling %s with args %s, %s" % (f.func_name, args, kw) -... return f(*args, **kw) +.. code-block:: python + + >>> @decorator + ... def trace(f, *args, **kw): + ... print "calling %s with args %s, %s" % (f.func_name, args, kw) + ... return f(*args, **kw) and now ``trace`` will be a decorator. You can easily check that the signature has changed: ->>> print getargspec(trace) -(['f'], None, None, None) +.. code-block:: python + + >>> print getargspec(trace) + (['f'], None, None, None) Therefore now ``trace`` can be used as a decorator and the following will work: ->>> @trace -... def func(): pass +.. code-block:: python + + >>> @trace + ... def func(): pass ->>> func() -calling func with args (), {} + >>> func() + calling func with args (), {} For the rest of this document, I will discuss examples of useful decorators built on top of ``decorator``. -``async`` --------------------------------------------- - -Here I show a decorator -which is able to convert a blocking procedure into an asynchronous -procedure. The procedure, when called, -is executed in a separate thread. The implementation is not difficult: - -$$_async -$$async - -``async`` as intended to be used on procedures, i.e. -on functions returning ``None``, since the return value of the original -function is discarded by this implementation. The decorated function returns -the current execution thread, which can be stored and checked later, for -instance to verify that the thread ``.isAlive()``. - -Here is an example of usage. Suppose one wants to write some data to -an external resource which can be accessed by a single user at once -(for instance a printer). Then the access to the writing function must -be locked. Here is a minimalistic example: - ->>> datalist = [] # for simplicity the written data are stored into a list. - ->>> @async -... def write(data): -... # append data to the datalist by locking -... with threading.Lock(): -... time.sleep(1) # emulate some long running operation -... datalist.append(data) -... # other operations not requiring a lock here - -Each call to ``write`` will create a new writer thread, but there will -be no synchronization problems since ``write`` is locked. - ->>> write("data1") - - ->>> time.sleep(.1) # wait a bit, so we are sure data2 is written after data1 - ->>> write("data2") - - ->>> time.sleep(2) # wait for the writers to complete - ->>> print datalist -['data1', 'data2'] - ``blocking`` ------------------------------------------- @@ -331,8 +308,7 @@ $$blocking (notice that without the help of ``decorator``, an additional level of nesting would have been needed). This is actually an example -of a one-parameter family of decorators where the -"busy message" is the parameter. +of a one-parameter family of decorators. Functions decorated with ``blocking`` will return a busy message if the resource is unavailable, and the intended result if the resource is @@ -360,101 +336,189 @@ available. For instance: >>> print read_data() some data -decorator factories --------------------------------------------------------------------- - -We have just seen an example -of a simple decorator factories, implemented as a function returning a -decorator. For more complex situations, it is more convenient to -implement decorator factories as classes returning callable objects -that can be used as signature-preserving decorators. +``async`` +-------------------------------------------- -To give an example of usage, let me -show a (simplistic) permission system based on classes. -Suppose we have a (Web) framework with the following user classes: +We have just seen an examples of a simple decorator factory, +implemented as a function returning a decorator. +For more complex situations, it is more +convenient to implement decorator factories as classes returning +callable objects that can be used as signature-preserving +decorators. The suggested pattern to do that is to introduce +a helper method ``call(self, func, *args, **kw)`` and to call +it in the ``__call__(self, func)`` method. + +As an example, here I show a decorator +which is able to convert a blocking function into an asynchronous +function. The function, when called, +is executed in a separate thread. Moreover, it is possible to set +three callbacks ``on_success``, ``on_failure`` and ``on_closing``, +to specify how to manage the function call. +The implementation is the following: + +$$on_success +$$on_failure +$$on_closing +$$Async + +The decorated function returns +the current execution thread, which can be stored and checked later, for +instance to verify that the thread ``.isAlive()``. -$$User -$$PowerUser -$$Admin +Here is an example of usage. Suppose one wants to write some data to +an external resource which can be accessed by a single user at once +(for instance a printer). Then the access to the writing function must +be locked. Here is a minimalistic example: -Suppose we have a function ``get_userclass`` returning the class of -the user logged in our system: in a Web framework ``get_userclass`` -will read the current user from the environment (i.e. from REMOTE_USER) -and will compare it with a database table to determine her user class. -For the sake of the example, let us use a trivial function: +.. code-block:: python -$$get_userclass - -We can implement the ``Restricted`` decorator factory as follows: + >>> async = Async(threading.Thread) -$$Restricted -$$PermissionError + >>> datalist = [] # for simplicity the written data are stored into a list. -An user can perform different actions according to her class: + >>> @async + ... def write(data): + ... # append data to the datalist by locking + ... with threading.Lock(): + ... time.sleep(1) # emulate some long running operation + ... datalist.append(data) + ... # other operations not requiring a lock here -$$Action +Each call to ``write`` will create a new writer thread, but there will +be no synchronization problems since ``write`` is locked. -Here is an example of usage:: +>>> write("data1") + - >>> a = Action() - >>> a.view() - >>> a.insert() - Traceback (most recent call last): - ... - PermissionError: User does not have the permission to run insert! - >>> a.delete() - Traceback (most recent call last): - ... - PermissionError: User does not have the permission to run delete! +>>> time.sleep(.1) # wait a bit, so we are sure data2 is written after data1 -A ``PowerUser`` could call ``.insert`` but not ``.delete``, whereas -and ``Admin`` can call all the methods. +>>> write("data2") + -I could have provided the same functionality by means of a mixin class -(say ``DecoratorMixin``) providing a ``__call__`` method. Within -that design an user should have derived his decorator class from -``DecoratorMixin``. However, `I generally dislike inheritance`_ -and I do not want to force my users to inherit from a class of my -choice. Using the class decorator approach my user is free to use -any class she wants, inheriting from any class she wants, provided -the class provide a proper ``.call`` method and does not provide -a custom ``__call__`` method. In other words, I am trading (less stringent) -interface requirements for (more stringent) inheritance requirements. +>>> time.sleep(2) # wait for the writers to complete -.. _I generally dislike inheritance: http://stacktrace.it/articoli/2008/06/i-pericoli-della-programmazione-con-i-mixin1 +>>> print datalist +['data1', 'data2'] The ``FunctionMaker`` class --------------------------------------------------------------- -The public API of the ``decorator`` module consists in the -``decorator`` function and its two attributes ``decorator`` and -``decorator_apply``. Internally, the functionality is implemented via +You may wonder about how the functionality of the ``decorator`` module +is implemented. The basic building block is a ``FunctionMaker`` class which is able to generate on the fly -functions with a given name and signature. You should not need to -resort to ``FunctionMaker`` when writing ordinary decorators, but it -is interesting to know how the module works internally, so I have -decided to add this paragraph. Notice that while I do not have plan +functions with a given name and signature from a function template +passed as a string. Generally speaking, you should not need to +resort to ``FunctionMaker`` when writing ordinary decorators, but +it is handy in some circumstances. We will see an example in two +paragraphs, when implementing a custom decorator factory +(``decorator_apply``). + +Notice that while I do not have plans to change or remove the functionality provided in the ``FunctionMaker`` class, I do not guarantee that it will stay -unchanged forever. On the other hand, the functionality provided by +unchanged forever. For instance, right now I am using the traditional +string interpolation syntax for function templates, but Python 2.6 +and Python 3.0 provide a newer interpolation syntax and I may use +the new syntax in the future. +On the other hand, the functionality provided by ``decorator`` has been there from version 0.1 and it is guaranteed to stay there forever. -``FunctionMaker`` takes the name and the signature of a function in -input, or a whole function. Here is an example of how to -restrict the signature of a function: + +``FunctionMaker`` takes the name and the signature (as a string) of a +function in input, or a whole function. Then, it creates a new +function (actually a closure) from a function template (the function +template must begin with ``def`` with no comments before and you cannot +use a ``lambda``) via its +``.make`` method: the name and the signature of the resulting function +are determinated by the specified name and signature. For instance, +here is an example of how to restrict the signature of a function: .. code-block:: python - >>> def f(*args, **kw): + >>> def f(*args, **kw): # a function with a generic signature ... print args, kw - >>> f1 = FunctionMaker(name="f1", signature="a,b").make(''' + >>> fun = FunctionMaker(name="f1", signature="a,b") + >>> f1 = fun.make('''\ ... def %(name)s(%(signature)s): ... f(%(signature)s)''', dict(f=f)) - + ... >>> f1(1,2) (1, 2) {} +The dictionary passed in this example (``dict(f=f)``) is the +execution environment: ``FunctionMaker.make`` actually returns a +closure, and the original function ``f`` is a variable in the +closure environment. +``FunctionMaker.make`` also accepts keyword arguments and such +arguments are attached to the resulting function. This is useful +if you want to set some function attributes, for instance the +docstring ``__doc__``. + +For debugging/introspection purposes it may be useful to see +the source code of the generated function; to do that, just +pass the flag ``addsource=True`` and a ``__source__`` attribute will +be added to the decorated function: + +.. code-block:: python + + >>> f1 = fun.make('''\ + ... def %(name)s(%(signature)s): + ... f(%(signature)s)''', dict(f=f), addsource=True) + ... + >>> print f1.__source__ + def f1(a,b): + f(a,b) + + +Getting the source code +--------------------------------------------------- + +Internally ``FunctionMaker.make`` uses ``exec`` to generate the +decorated function. Therefore +``inspect.getsource`` will not work for decorated functions. That +means that the usual '??' trick in IPython will give you the (right on +the spot) message ``Dynamically generated function. No source code +available``. In the past I have considered this acceptable, since +``inspect.getsource`` does not really work even with regular +decorators. In that case ``inspect.getsource`` gives you the wrapper +source code which is probably not what you want: + +$$identity_dec + +.. code-block:: python + + @identity_dec + def example(): pass + + >>> print getsource(example) + def wrapper(*args, **kw): + return func(*args, **kw) + + +(see bug report 1764286_ for an explanation of what is happening). +Unfortunately the bug is still there, even in Python 2.6 and 3.0. +There is however a workaround. The decorator module adds an +attribute ``.undecorated`` to the decorated function, containing +a reference to the original function. The easy way to get +the source code is to call ``inspect.getsource`` on the +undecorated function: + +.. code-block:: python + + >>> print getsource(factorial.undecorated) + @tail_recursive + def factorial(n, acc=1): + "The good old factorial" + if n == 0: return acc + return factorial(n-1, n*acc) + + +.. _1764286: http://bugs.python.org/issue1764286 + +Dealing with third party decorators +----------------------------------------------------------------- + Sometimes you find on the net some cool decorator that you would like to include in your code. However, more often than not the cool decorator is not signature-preserving. Therefore you may want an easy way to @@ -464,15 +528,16 @@ having to rewrite them in terms of ``decorator``. You can use a $$decorator_apply +``decorator_apply`` sets the attribute ``.undecorated`` of the generated +function to the original function, so that you can get the right +source code. + Notice that I am not providing this functionality in the ``decorator`` -module directly since I think it is best to rewrite a decorator rather +module directly since I think it is best to rewrite the decorator rather than adding an additional level of indirection. However, practicality beats purity, so you can add ``decorator_apply`` to your toolbox and use it if you need to. -``tail-recursive`` ------------------------------------------------------------- - In order to give an example of usage of ``decorator_apply``, I will show a pretty slick decorator that converts a tail-recursive function in an iterative function. I have shamelessly stolen the basic idea from Kay Schluehr's recipe @@ -488,13 +553,9 @@ $$tail_recursive Here is how you apply the upgraded decorator to the good old factorial: -.. code-block:: python +$$factorial - @tail_recursive - def factorial(n, acc=1): - "The good old factorial" - if n == 0: return acc - return factorial(n-1, n*acc) +.. code-block:: python >>> print factorial(4) 24 @@ -503,63 +564,14 @@ This decorator is pretty impressive, and should give you some food for your mind ;) Notice that there is no recursion limit now, and you can easily compute ``factorial(1001)`` or larger without filling the stack frame. Notice also that the decorator will not work on functions which -are not tail recursive, such as +are not tail recursive, such as the following $$fact -(a function is tail recursive if it either returns a value without +(reminder: a function is tail recursive if it either returns a value without making a recursive call, or returns directly the result of a recursive call). -Getting the source code ---------------------------------------------------- - -Iinternally the decorator module uses ``exec`` to generate the decorated -function with the right signature. Therefore the ordinary -``inspect.getsource`` will not work for decorated -functions. This means that the usual '??' trick in IPython will give you -the (right on the spot) message -``Dynamically generated function. No source code available.``. -In the past I have considered this acceptable, since ``inspect.getsource`` -does not really work even with regular decorators. In that case -``inspect.getsource`` gives you the wrapper source code which is probably -not what you want: - -$$identity_dec -$$example - ->>> import inspect ->>> print inspect.getsource(example) - def wrapper(*args, **kw): - return func(*args, **kw) - - -(see bug report 1764286_ for an explanation of what is happening). -Unfortunately the bug is still there, even in Python 2.6 and 3.0. -There is however a workaround. The decorator module adds an -attribute ``.undecorated`` to the decorated function, containing -a reference to the original function. The easy way to get -the source code is to call ``inspect.getsource`` on the -undecorated function: - ->>> print inspect.getsource(factorial.undecorated) -@tail_recursive -def factorial(n, acc=1): - "The good old factorial" - if n == 0: return acc - return factorial(n-1, n*acc) - - -.. _1764286: http://bugs.python.org/issue1764286 - -Starting from release 3.0, the decorator module also adds -a ``__source__`` attribute to the decorated function. - -The generated function is a closure depending on the the caller -``_call_`` and the original function ``_func_``. For debugging convenience -you get the names of the moduled where they are defined in a comment: -in this example they are defined in the ``__main__`` module. - Caveats and limitations ------------------------------------------- @@ -585,12 +597,12 @@ The worse case is shown by the following example:: pass " "f()" -On my Linux system, using the ``do_nothing`` decorator instead of the -plain function is more than four times slower:: +On my MacBook, using the ``do_nothing`` decorator instead of the +plain function is more than three times slower:: - $ bash performance.sh - 1000000 loops, best of 3: 1.68 usec per loop - 1000000 loops, best of 3: 0.397 usec per loop + $ bash performance.sh + 1000000 loops, best of 3: 0.995 usec per loop + 1000000 loops, best of 3: 0.273 usec per loop It should be noted that a real life function would probably do something more useful than ``f`` here, and therefore in real life the @@ -601,23 +613,26 @@ a penalty in your specific use case is to measure it. You should be aware that decorators will make your tracebacks longer and more difficult to understand. Consider this example: ->>> @trace -... def f(): -... 1/0 +.. code-block:: python + + >>> @trace + ... def f(): + ... 1/0 Calling ``f()`` will give you a ``ZeroDivisionError``, but since the function is decorated the traceback will be longer: ->>> f() -Traceback (most recent call last): - File "", line 1, in ? - f() - File "", line 2, in f - File "", line 4, in trace - return f(*args, **kw) - File "", line 3, in f - 1/0 -ZeroDivisionError: integer division or modulo by zero +.. code-block:: python + + >>> f() + calling f with args (), {} + Traceback (most recent call last): + File "", line 1, in + File "", line 2, in f + File "documentation.py", line 799, in _trace + return f(*args, **kw) + File "", line 3, in f + ZeroDivisionError: integer division or modulo by zero You see here the inner call to the decorator ``trace``, which calls ``f(*args, **kw)``, and a reference to ``File "", line 2, in f``. @@ -633,8 +648,8 @@ add an hook to make it possible to change their signature directly. That could happen in future versions of Python (see PEP 362_) and then the decorator module would become obsolete. However, at present, even in Python 3.0 it is impossible to change the function signature -directly, therefore the ``decorator`` module is still useful (this is -the reason why I am releasing version 3.0). +directly, therefore the ``decorator`` module is still useful. +Actually, this is one of the main reasons why I am releasing version 3.0. .. _362: http://www.python.org/dev/peps/pep-0362 @@ -642,49 +657,54 @@ In the present implementation, decorators generated by ``decorator`` can only be used on user-defined Python functions or methods, not on generic callable objects, nor on built-in functions, due to limitations of the ``inspect`` module in the standard library. - -Moreover, you can decorate anonymous functions: - ->>> trace(lambda : None)() -calling with args (), {} There is a restriction on the names of the arguments: for instance, if try to call an argument ``_call_`` or ``_func_`` you will get a ``NameError``: ->>> @trace -... def f(_func_): print f -... -Traceback (most recent call last): - ... -NameError: _func_ is overridden in -def f(_func_): - return _call_(_func_, _func_) +.. code-block:: python + + >>> @trace + ... def f(_func_): print f + ... + Traceback (most recent call last): + ... + NameError: _func_ is overridden in + def f(_func_): + return _call_(_func_, _func_) Finally, the implementation is such that the decorated function contains -a copy of the original function attributes: +a *copy* of the original function dictionary +(``vars(decorated_f) is not vars(f)``): ->>> def f(): pass # the original function ->>> f.attr1 = "something" # setting an attribute ->>> f.attr2 = "something else" # setting another attribute +.. code-block:: python ->>> traced_f = trace(f) # the decorated function + >>> def f(): pass # the original function + >>> f.attr1 = "something" # setting an attribute + >>> f.attr2 = "something else" # setting another attribute ->>> traced_f.attr1 -'something' ->>> traced_f.attr2 = "something different" # setting attr ->>> f.attr2 # the original attribute did not change -'something else' + >>> traced_f = trace(f) # the decorated function -Backward compatibility notes + >>> traced_f.attr1 + 'something' + >>> traced_f.attr2 = "something different" # setting attr + >>> f.attr2 # the original attribute did not change + 'something else' + +Compatibility notes --------------------------------------------------------------- Version 3.0 is a complete rewrite of the original implementation. It is mostly compatible with the past, a part for a few differences. -The utilites ``get_info`` and ``new_wrapper``, available +First of all, the utilites ``get_info`` and ``new_wrapper``, available in the 2.X versions, have been deprecated and they will be removed in the future. For the moment, using them raises a ``DeprecationWarning``. +Incidentally, the functionality has been implemented through a +decorator which makes a good example for this documentation: + +$$deprecated + ``get_info`` has been removed since it was little used and since it had to be changed anyway to work with Python 3.0; ``new_wrapper`` has been removed since it was useless: its major use case (converting @@ -695,24 +715,32 @@ and the other use case can be managed with the ``FunctionMaker``. Finally ``decorator`` cannot be used as a class decorator and the `functionality introduced in version 2.3`_ has been removed. That means that in order to define decorator factories with classes you -need to override the ``__call__`` method explicitly (no magic anymore). +need to define the ``__call__`` method explicitly (no magic anymore). All these changes should not cause any trouble, since they were -all rarely used features. Should you have trouble, you are invited to +all rarely used features. Should you have any trouble, you can always downgrade to the 2.3 version. -.. _functionality introduced in version 2.3: http://www.phyast.pitt.edu/~micheles/python/documentation.html#class-decorators-and-decorator-factories - -Python 3.0 support ------------------------------------------------------------- - The examples shown here have been tested with Python 2.5. Python 2.4 is also supported - of course the examples requiring the ``with`` -statement will not work there - as well as Python 2.5. Python 3.0 -is supported too. Simply run the script ``2to3`` on the module +statement will not work there. Python 2.6 works fine, but if you +run the examples here in the interactive interpreter +you will notice a couple of minor differences since +``getargspec`` returns an ``ArgSpec`` namedtuple instead of a regular +tuple, and the string representation of a thread object returns a +thread identifier number. That means that running the file +``documentation.py`` under Python 2.5 will a few errors, but +they are not serious. Python 3.0 is kind of supported too. +Simply run the script ``2to3`` on the module ``decorator.py`` and you will get a version of the code running -with Python 3.0. Notice however that the decorator module is little -tested with Python 3.0, since I mostly use Python 2.5. +with Python 3.0 (at least, I did some simple checks and it seemed +to work). However there is no support for `function annotations`_ yet +since it seems premature at this moment (most people are +still using Python 2.5). + +.. _functionality introduced in version 2.3: http://www.phyast.pitt.edu/~micheles/python/documentation.html#class-decorators-and-decorator-factories +.. _function annotations: http://www.python.org/dev/peps/pep-3107/ + LICENCE --------------------------------------------- @@ -746,7 +774,11 @@ note, just to gratify my ego. On the other hand, if you use this software and you are unhappy with it, send me a patch! """ from __future__ import with_statement -import sys, threading, time, functools, inspect, itertools +import sys, threading, time, functools, inspect, itertools +try: + import multiprocessing +except ImportError: + import processing as multiprocessing from decorator import * from setup import VERSION @@ -768,17 +800,54 @@ def _trace(f, *args, **kw): def trace(f): return decorator(_trace, f) -def _async(proc, *args, **kw): - name = '%s-%s' % (proc.__name__, proc.counter.next()) - thread = threading.Thread(None, proc, name, args, kw) - thread.start() - return thread +def on_success(result): # default implementation + "Called on the result of the function" + return result + +def on_failure(exc_info): # default implementation + "Called if the function fails" + pass + +def on_closing(): # default implementation + "Called at the end, both in case of success and failure" + pass + +class Async(object): + """ + A decorator converting blocking functions into asynchronous + functions, by using threads or processes. Examples: + + async_with_threads = Async(threading.Thread) + async_with_processes = Async(multiprocessing.Process) + """ + + def __init__(self, threadfactory): + self.threadfactory = threadfactory + + def __call__(self, func, on_success=on_success, + on_failure=on_failure, on_closing=on_closing): + # every decorated function has its own independent thread counter + func.counter = itertools.count(1) + func.on_success = on_success + func.on_failure = on_failure + func.on_closing = on_closing + return decorator(self.call, func) + + def call(self, func, *args, **kw): + def func_wrapper(): + try: + result = func(*args, **kw) + except: + func.on_failure(sys.exc_info()) + else: + return func.on_success(result) + finally: + func.on_closing() + name = '%s-%s' % (func.__name__, func.counter.next()) + thread = self.threadfactory(None, func_wrapper, name) + thread.start() + return thread -def async(proc): - # every decorated procedure has its own independent thread counter - proc.counter = itertools.count(1) - return decorator(_async, proc) - def identity_dec(func): def wrapper(*args, **kw): return func(*args, **kw) @@ -790,7 +859,7 @@ def example(): pass def memoize25(func): func.cache = {} def memoize(*args, **kw): - if kw: + if kw: # frozenset is used to ensure hashability key = args, frozenset(kw.iteritems()) else: key = args @@ -803,12 +872,11 @@ def memoize25(func): return functools.update_wrapper(memoize, func) def _memoize(func, *args, **kw): - # args and kw must be hashable - if kw: + if kw: # frozenset is used to ensure hashability key = args, frozenset(kw.iteritems()) else: key = args - cache = func.cache + cache = func.cache # attributed added by memoize if key in cache: return cache[key] else: diff --git a/other.txt b/other.txt deleted file mode 100755 index 3eddd5c..0000000 --- a/other.txt +++ /dev/null @@ -1,125 +0,0 @@ ->>> from examples import deferred - ->>> fac = deferred(0.0) - ->>> results = [] # or use a Queue, if you wish - ->>> def f(x): -... "In real life, should perform some computation on x" -... results.append(x) - ->>> action["user1"] = fac(f) ->>> action["user2"] = fac(f) - ->>> f1("arg1"); print f1.thread -<_Timer(Thread-1, started)> - ->>> f2("arg2"); print f2.thread -<_Timer(Thread-2, started)> - ->>> time.sleep(.4) ->>> print results -['arg1', 'arg2'] - - # - - import time, threading - from decorator import decorator - - @decorator - def blocking(proc, *args, **kw): - thread = getattr(proc, "thread", None) - if thread is None: - proc.thread = threading.Thread(None, proc, args, kw) - proc.thread.start() - elif thread.isAlive(): - raise AccessError("Resource locked!") - else: - proc.thread = None - blocking.copy = True - - # - ->>> from examples import threaded ->>> def f(): -... print "done" - ->>> read1, read2 = blocking(readinput), blocking(readinput) ->>> read1(), read2() -done -done - -Thread factories ---------------------------------------------- - - # - - import threading - - @decorator - def threadfactory(f, *args, **kw): - f.created = getattr(f, "created", 0) + 1 - return threading.Thread(None, f, f.__name__ + str(f.created), args, kw) - - # - -Here the decorator takes a regular function and convert it into a -thread factory. The name of the generated thread is given by -the name of the function plus an integer number, counting how -many threads have been created by the factory. - ->>> from examples import threadfactory - ->>> @threadfactory -... def do_action(): -... "doing something in a separate thread." - - ->>> action1 = do_action() # create a first thread ->>> print action1 - - ->>> action2 = do_action() # create a second thread ->>> action2.start() # start it ->>> print action2 - - -The ``.created`` attribute stores the total number of created threads: - ->>> print do_action.created -2 -The thread object also stores the result of the function call. - - # - - def delayed(nsec): - def call(func, *args, **kw): - def set_result(): thread.result = func(*args, **kw) - thread = threading.Timer(nsec, set_result) - thread.result = "Not available" - thread.start() - return thread - return decorator(call) - - # - -Here is an example of usage:: - - # - - valuelist = [] - - def send_to_external_process(value): - time.sleep(.1) # simulate some time delay - valuelist.append(value) - - @delayed(.2) # give time to the value to reach the external process - def get_from_external_process(): - return valuelist.pop() - - - # - ->>> send_to_external_process("value") ->>> print get_from_external_process() -value diff --git a/setup.py b/setup.py index 3b18292..ea094e8 100644 --- a/setup.py +++ b/setup.py @@ -6,26 +6,23 @@ except ImportError: VERSION = '3.0.0' if __name__ == '__main__': + try: + docfile = file('/tmp/documentation.html') + except IOError: # file not found, ignore + doc = '' + else: + doc = docfile.read() setup(name='decorator', version=VERSION, description='Better living through Python with decorators', - long_description="""\ - As of now, writing custom decorators correctly requires some experience - and it is not as easy as it could be. For instance, typical implementations - of decorators involve nested functions, and we all know - that flat is better than nested. Moreover, typical implementations - of decorators do not preserve the signature of decorated functions, - thus confusing both documentation tools and developers. - - The aim of the decorator module it to simplify the usage of decorators - for the average programmer, and to popularize decorators usage giving - examples of useful decorators, such as memoize, tracing, threaded, etc.""", + long_description=doc, author='Michele Simionato', author_email='michele.simionato@gmail.com', url='http://pypi.python.org/pypi/decorator', license="BSD License", py_modules = ['decorator'], keywords="decorators generic utility", + platforms=["All"], classifiers=['Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', @@ -34,5 +31,5 @@ if __name__ == '__main__': 'Programming Language :: Python', 'Topic :: Software Development :: Libraries', 'Topic :: Utilities'], - zip_safe=False) + zip_safe=False) diff --git a/util.py b/util.py deleted file mode 100755 index 80e9037..0000000 --- a/util.py +++ /dev/null @@ -1,14 +0,0 @@ -""" -A few useful decorators -""" - -import sys, time -from decorator import decorator - -@decorator -def traced(func, *args, **kw): - t1 = time.time() - res = func(*args,**kw) - t2 = time.time() - print >> sys.stderr, func.__name__, args, 'TIME:', t2-t1 - return res -- cgit v1.2.1 From cea222153dbe37f41a3f38257fee69aadde37d45 Mon Sep 17 00:00:00 2001 From: "michele.simionato" Date: Sun, 14 Dec 2008 07:00:12 +0000 Subject: Added the .html documentation to the distribution --- MANIFEST.in | 2 +- Makefile | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/MANIFEST.in b/MANIFEST.in index 4ef4f14..95faa9b 100644 --- a/MANIFEST.in +++ b/MANIFEST.in @@ -1 +1 @@ -include documentation.pdf +include documentation.html documentation.pdf diff --git a/Makefile b/Makefile index 52405ac..41eab7c 100644 --- a/Makefile +++ b/Makefile @@ -1,6 +1,6 @@ RST=/home/micheles/trunk/ROnline/RCommon/Python/ms/tools/rst.py pdf: /tmp/documentation.rst - $(RST) -ptd /tmp/documentation.rst; mv /tmp/documentation.pdf . + $(RST) -ptd /tmp/documentation.rst; cp /tmp/documentation.pdf /tmp/documentation.html . upload: documentation.pdf python setup.py register sdist upload -- cgit v1.2.1 From 14f21992851753f316ee1a000bcc9e08c7980b3d Mon Sep 17 00:00:00 2001 From: "michele.simionato" Date: Fri, 19 Dec 2008 08:08:14 +0000 Subject: Excluded the Makefile from MANIFEST.in --- MANIFEST.in | 1 + 1 file changed, 1 insertion(+) diff --git a/MANIFEST.in b/MANIFEST.in index 95faa9b..78a2129 100644 --- a/MANIFEST.in +++ b/MANIFEST.in @@ -1 +1,2 @@ include documentation.html documentation.pdf +exclude Makefile -- cgit v1.2.1 From f3822baacd13ea07dd82bfa98ccf77db34548fe8 Mon Sep 17 00:00:00 2001 From: "michele.simionato" Date: Tue, 23 Dec 2008 16:53:57 +0000 Subject: Fixed the link to the documentation page --- documentation.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/documentation.py b/documentation.py index cdc0685..11b2078 100644 --- a/documentation.py +++ b/documentation.py @@ -6,7 +6,7 @@ The ``decorator`` module :E-mail: michele.simionato@gmail.com :Version: $VERSION ($DATE) :Requires: Python 2.4+ -:Download page: http://pypi.python.org/pypi/decorator +:Download page: http://pypi.python.org/pypi/decorator/$VERSION :Installation: ``easy_install decorator`` :License: BSD license -- cgit v1.2.1 From 53aea0e07b603b1f617b33a7c4ace8bd7e288981 Mon Sep 17 00:00:00 2001 From: "michele.simionato" Date: Fri, 9 Jan 2009 08:28:09 +0000 Subject: Hacked setup.py to upload the documentation in a beatiful format, following the comment on http://www.artima.com/weblogs/viewpost.jsp?thread=245050 --- documentation.py | 5 +---- setup.py | 2 +- 2 files changed, 2 insertions(+), 5 deletions(-) diff --git a/documentation.py b/documentation.py index 11b2078..82b4fa4 100644 --- a/documentation.py +++ b/documentation.py @@ -775,10 +775,7 @@ you are unhappy with it, send me a patch! """ from __future__ import with_statement import sys, threading, time, functools, inspect, itertools -try: - import multiprocessing -except ImportError: - import processing as multiprocessing +import multiprocessing from decorator import * from setup import VERSION diff --git a/setup.py b/setup.py index ea094e8..f56a3b1 100644 --- a/setup.py +++ b/setup.py @@ -15,7 +15,7 @@ if __name__ == '__main__': setup(name='decorator', version=VERSION, description='Better living through Python with decorators', - long_description=doc, + long_description='%s
' % doc,
           author='Michele Simionato',
           author_email='michele.simionato@gmail.com',
           url='http://pypi.python.org/pypi/decorator',
-- 
cgit v1.2.1


From d1f45f65e6150e3c16d261375df400b3e7e5f89b Mon Sep 17 00:00:00 2001
From: "michele.simionato" 
Date: Mon, 16 Feb 2009 06:14:07 +0000
Subject: Version 3.0.1 released

---
 CHANGES.txt      |  3 +++
 Makefile         |  3 +++
 decorator.py     |  7 +++++--
 documentation.py | 51 +++++++++++++++++++++++++++++++++++++++++----------
 setup.py         |  2 +-
 5 files changed, 53 insertions(+), 13 deletions(-)

diff --git a/CHANGES.txt b/CHANGES.txt
index 852ca8b..dc09489 100755
--- a/CHANGES.txt
+++ b/CHANGES.txt
@@ -1,6 +1,9 @@
 HISTORY
 ----------
 
+3.0.1. Improved the error message in case a bound/unbound method is passed
+     instead of a function and documented this case; that should make life
+     easier for users like Gustavo Nerea (16/02/2009)
 3.0. New major version introducing ``FunctionMaker`` and the two-argument
      syntax for ``decorator``. Moreover, added support for getting the
      source code. This version is Python 3.0 ready.
diff --git a/Makefile b/Makefile
index 41eab7c..35d92a5 100644
--- a/Makefile
+++ b/Makefile
@@ -1,5 +1,8 @@
 RST=/home/micheles/trunk/ROnline/RCommon/Python/ms/tools/rst.py
 
+rst: documentation.py
+	python /home/micheles/trunk/ROnline/RCommon/Python/ms/tools/minidoc.py -dH documentation.py
+
 pdf: /tmp/documentation.rst
 	$(RST) -ptd /tmp/documentation.rst; cp /tmp/documentation.pdf /tmp/documentation.html .
 upload: documentation.pdf
diff --git a/decorator.py b/decorator.py
index ea38aeb..d775a67 100755
--- a/decorator.py
+++ b/decorator.py
@@ -40,7 +40,8 @@ class FunctionMaker(object):
     """
     def __init__(self, func=None, name=None, signature=None,
                  defaults=None, doc=None, module=None, funcdict=None):
-        if func: # func can also be a class or a callable
+        if func:
+            # func can also be a class or a callable, but not an instance method
             self.name = func.__name__
             if self.name == '': # small hack for lambda functions
                 self.name = '_lambda_' 
@@ -64,7 +65,9 @@ class FunctionMaker(object):
         if funcdict:
             self.dict = funcdict
         # check existence required attributes
-        assert self.name and hasattr(self, 'signature')
+        assert hasattr(self, 'name')
+        if not hasattr(self, 'signature'):
+            raise TypeError('You are decorating a non function: %s' % func)
 
     def update(self, func, **kw):
         "Update the signature of func with the data in self"
diff --git a/documentation.py b/documentation.py
index 82b4fa4..665e45c 100644
--- a/documentation.py
+++ b/documentation.py
@@ -491,7 +491,7 @@ $$identity_dec
  @identity_dec
  def example(): pass
 
- >>> print getsource(example)
+ >>> print inspect.getsource(example)
      def wrapper(*args, **kw):
          return func(*args, **kw)
  
@@ -506,7 +506,7 @@ undecorated function:
 
 .. code-block:: python
 
- >>> print getsource(factorial.undecorated)
+ >>> print inspect.getsource(factorial.undecorated)
  @tail_recursive
  def factorial(n, acc=1):
      "The good old factorial"
@@ -625,13 +625,13 @@ function is decorated the traceback will be longer:
 .. code-block:: python
 
  >>> f()
- calling f with args (), {}
  Traceback (most recent call last):
-   File "", line 1, in 
-   File "", line 2, in f
-   File "documentation.py", line 799, in _trace
-     return f(*args, **kw)
-   File "", line 3, in f
+   ...
+      File "", line 2, in f
+      File "", line 4, in trace
+        return f(*args, **kw)
+      File "", line 3, in f
+        1/0
  ZeroDivisionError: integer division or modulo by zero
 
 You see here the inner call to the decorator ``trace``, which calls 
@@ -656,8 +656,39 @@ Actually, this is one of the main reasons why I am releasing version 3.0.
 In the present implementation, decorators generated by ``decorator``
 can only be used on user-defined Python functions or methods, not on generic 
 callable objects, nor on built-in functions, due to limitations of the
-``inspect`` module in the standard library.
-    
+``inspect`` module in the standard library. Moreover, notice
+that you can decorate a method, but only before if becomes a bound or unbound
+method, i.e. inside the class.
+Here is an example of valid decoration:
+
+.. code-block:: python
+
+ >>> class C(object): 
+ ...      @trace
+ ...      def meth(self):
+ ...          pass
+
+Here is an example of invalid decoration, when the decorator in
+called too late:
+
+.. code-block:: python
+
+ >>> class C(object):
+ ...      def meth(self):
+ ...          pass
+ ...
+ >>> trace(C.meth)
+ Traceback (most recent call last):
+   ...
+ TypeError: You are decorating a non function: 
+
+The solution is to extract the inner function from the unbound method:
+
+.. code-block:: python
+
+ >>> trace(C.meth.im_func) # doctest: +ELLIPSIS
+ 
+
 There is a restriction on the names of the arguments: for instance,
 if try to call an argument ``_call_`` or ``_func_``
 you will get a ``NameError``:
diff --git a/setup.py b/setup.py
index f56a3b1..83e990d 100644
--- a/setup.py
+++ b/setup.py
@@ -3,7 +3,7 @@ try:
 except ImportError:
     from distutils.core import setup
 
-VERSION = '3.0.0'
+VERSION = '3.0.1'
 
 if __name__ == '__main__':
     try:
-- 
cgit v1.2.1


From ed690fd6af1357d514c298bc4a3f84ef6f153486 Mon Sep 17 00:00:00 2001
From: "michele.simionato" 
Date: Wed, 15 Apr 2009 15:03:33 +0000
Subject: Added copyright notice to the decorator module as asked by Daniel
 Stutzbach

---
 decorator.py     | 5 ++++-
 documentation.py | 3 +++
 2 files changed, 7 insertions(+), 1 deletion(-)

diff --git a/decorator.py b/decorator.py
index d775a67..1a8db8b 100755
--- a/decorator.py
+++ b/decorator.py
@@ -1,5 +1,8 @@
 ##########################     LICENCE     ###############################
-      
+##
+##   Copyright (c) 2005, Michele Simionato
+##   All rights reserved.
+##
 ##   Redistributions of source code must retain the above copyright 
 ##   notice, this list of conditions and the following disclaimer.
 ##   Redistributions in bytecode form must reproduce the above copyright
diff --git a/documentation.py b/documentation.py
index 665e45c..97552da 100644
--- a/documentation.py
+++ b/documentation.py
@@ -780,6 +780,9 @@ Redistribution and use in source and binary forms, with or without
 modification, are permitted provided that the following conditions are
 met::
 
+  Copyright (c) 2005, Michele Simionato
+  All rights reserved.
+
   Redistributions of source code must retain the above copyright 
   notice, this list of conditions and the following disclaimer.
   Redistributions in bytecode form must reproduce the above copyright
-- 
cgit v1.2.1


From 4fab653aa6f1a2843daa9fa119673583c317ba7b Mon Sep 17 00:00:00 2001
From: "michele.simionato" 
Date: Tue, 21 Apr 2009 09:53:51 +0000
Subject: Improved the TailRecursive decorator by using George Sakkis's version

---
 documentation.py | 35 +++++++++++++++++------------------
 1 file changed, 17 insertions(+), 18 deletions(-)

diff --git a/documentation.py b/documentation.py
index 97552da..e5cc32c 100644
--- a/documentation.py
+++ b/documentation.py
@@ -983,37 +983,36 @@ class Action(object):
     @Restricted(Admin)
     def delete(self):
         pass
-    
+
 class TailRecursive(object):
     """
     tail_recursive decorator based on Kay Schluehr's recipe
     http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/496691
+    with improvements by me and George Sakkis.
     """
-    CONTINUE = object() # sentinel
 
     def __init__(self, func):
         self.func = func
         self.firstcall = True
+        self.CONTINUE = object() # sentinel
 
     def __call__(self, *args, **kwd):
-        try:
-            if self.firstcall: # start looping
-                self.firstcall = False
-                while True:            
-                    result = self.func(*args, **kwd)
-                    if result is self.CONTINUE: # update arguments
+        CONTINUE = self.CONTINUE
+        if self.firstcall:
+            func = self.func
+            self.firstcall = False
+            try:
+                while True:
+                    result = func(*args, **kwd)
+                    if result is CONTINUE: # update arguments
                         args, kwd = self.argskwd
                     else: # last call
-                        break
-            else: # return the arguments of the tail call
-                self.argskwd = args, kwd
-                return self.CONTINUE
-        except: # reset and re-raise
-            self.firstcall = True
-            raise
-        else: # reset and exit
-            self.firstcall = True 
-            return result
+                        return result
+            finally:
+                self.firstcall = True
+        else: # return the arguments of the tail call
+            self.argskwd = args, kwd
+            return CONTINUE
 
 def tail_recursive(func):
     return decorator_apply(TailRecursive, func)
-- 
cgit v1.2.1


From e9cda2473b617ef454e5ed2755d9c678c0603ca6 Mon Sep 17 00:00:00 2001
From: "michele.simionato" 
Date: Sun, 16 Aug 2009 12:53:00 +0000
Subject: Decorator module, version 3.1

---
 CHANGES.txt      |   6 +-
 decorator.py     |  56 +++++++++++++----
 documentation.py | 186 +++++++++++++++++++++++++++++++------------------------
 setup.py         |   2 +-
 4 files changed, 155 insertions(+), 95 deletions(-)

diff --git a/CHANGES.txt b/CHANGES.txt
index dc09489..00ccdef 100755
--- a/CHANGES.txt
+++ b/CHANGES.txt
@@ -1,6 +1,10 @@
 HISTORY
 ----------
 
+3.1. Added decorator.factory, an easy way to define families of decorators
+     (requested by various users, including David Laban). Refactored the
+     FunctionMaker class and added an easier to use .create classmethod.
+     Internally, functools.partial is used for Python >= 2.5 (16/08/2009)
 3.0.1. Improved the error message in case a bound/unbound method is passed
      instead of a function and documented this case; that should make life
      easier for users like Gustavo Nerea (16/02/2009)
@@ -8,7 +12,7 @@ HISTORY
      syntax for ``decorator``. Moreover, added support for getting the
      source code. This version is Python 3.0 ready.
      Major overhaul of the documentation, now hosted on 
-     http://packages.python.org/decorator (14/12/2008).
+     http://packages.python.org/decorator (14/12/2008)
 2.3.2. Small optimization in the code for decorator factories. First version
        with the code uploaded to PyPI (01/12/2008)
 2.3.1. Set the zipsafe flag to False, since I want my users to have the source, not
diff --git a/decorator.py b/decorator.py
index 1a8db8b..2a5c090 100755
--- a/decorator.py
+++ b/decorator.py
@@ -31,6 +31,15 @@ for the documentation.
 __all__ = ["decorator", "FunctionMaker", "deprecated", "getinfo", "new_wrapper"]
 
 import os, sys, re, inspect, warnings
+try:
+    from functools import partial
+except ImportError: # for Python version < 2.5
+    def partial(func, *args):
+        "A poor man replacement of partial for use in the decorator module only"
+        f = lambda *otherargs: func(*(args + otherargs))
+        f.args = args
+        f.func = func
+        return f
 
 DEF = re.compile('\s*def\s*([_\w][_\w\d]*)\s*\(')
 
@@ -77,7 +86,7 @@ class FunctionMaker(object):
         func.__name__ = self.name
         func.__doc__ = getattr(self, 'doc', None)
         func.__dict__ = getattr(self, 'dict', {})
-        func.func_defaults = getattr(self, 'defaults', None)
+        func.func_defaults = getattr(self, 'defaults', ())
         callermodule = sys._getframe(3).f_globals.get('__name__', '?')
         func.__module__ = getattr(self, 'module', callermodule)
         func.__dict__.update(kw)
@@ -110,23 +119,44 @@ class FunctionMaker(object):
         self.update(func, **attrs)
         return func
 
+    @classmethod
+    def create(cls, obj, body, evaldict, defaults=None, addsource=True,**attrs):
+        """
+        Create a function from the strings name, signature and body.
+        evaldict is the evaluation dictionary. If addsource is true an attribute
+        __source__ is added to the result. The attributes attrs are added,
+        if any.
+        """
+        if isinstance(obj, str): # "name(signature)"
+            name, rest = obj.strip().split('(', 1)
+            signature = rest[:-1]
+            func = None
+        else: # a function
+            name = None
+            signature = None
+            func = obj
+        fun = cls(func, name, signature, defaults)
+        ibody = ''.join('    ' + line for line in body.splitlines())
+        return fun.make('def %(name)s(%(signature)s):\n' + ibody, 
+                        evaldict, addsource, **attrs)
+  
 def decorator(caller, func=None):
     """
     decorator(caller) converts a caller function into a decorator;
     decorator(caller, func) decorates a function using a caller.
     """
-    if func is None: # returns a decorator
-        fun = FunctionMaker(caller)
-        first_arg = inspect.getargspec(caller)[0][0]
-        src = 'def %s(%s): return _call_(caller, %s)' % (
-            caller.__name__, first_arg, first_arg)
-        return fun.make(src, dict(caller=caller, _call_=decorator),
-                        undecorated=caller)
-    else: # returns a decorated function
-        fun = FunctionMaker(func)
-        src = """def %(name)s(%(signature)s):
-    return _call_(_func_, %(signature)s)"""
-        return fun.make(src, dict(_func_=func, _call_=caller), undecorated=func)
+    if func is not None: # returns a decorated function
+        return FunctionMaker.create(
+            func, "return _call_(_func_, %(signature)s)",
+            dict(_call_=caller, _func_=func), undecorated=func)
+    else: # returns a decorator
+        return partial(decorator, caller)
+
+def decorator_factory(decfac):
+    "decorator.factory(decfac) returns a one-parameter family of decorators"
+    return partial(lambda df, param: decorator(partial(df, param)), decfac)
+
+decorator.factory = decorator_factory
 
 ###################### deprecated functionality #########################
 
diff --git a/documentation.py b/documentation.py
index e5cc32c..2452333 100644
--- a/documentation.py
+++ b/documentation.py
@@ -275,16 +275,15 @@ For instance, you can write directly
  ...     print "calling %s with args %s, %s" % (f.func_name, args, kw)
  ...     return f(*args, **kw)
 
-and now ``trace`` will be a decorator. You
-can easily check that the signature has changed:
+and now ``trace`` will be a decorator. Actually ``trace`` is a ``partial``
+object which can be used as a decorator:
 
 .. code-block:: python
 
- >>> print getargspec(trace)
- (['f'], None, None, None)
+ >>> trace # doctest: +ELLIPSIS
+ 
 
-Therefore now ``trace`` can be used as a decorator and
-the following will work:
+Here is an example of usage:
 
 .. code-block:: python
 
@@ -294,21 +293,59 @@ the following will work:
  >>> func()
  calling func with args (), {}
 
-For the rest of this document, I will discuss examples of useful
-decorators built on top of ``decorator``.
+If you are using an old Python version (Python 2.4) the
+``decorator`` module provides a poor man replacement for
+``functools.partial`` as a higher order function.
+
+There is also an easy way to create one-parameter factories of
+decorators. Suppose for instance you want to generated different
+tracing generator, with different tracing messages.
+Here is how to do it:
+
+.. code-block:: python
+
+ >>> @decorator.factory
+ ... def trace_factory(message_template, f, *args, **kw):
+ ...     name = f.func_name
+ ...     print message_template % locals()
+ ...     return f(*args, **kw)
+
+``decorator.factory`` converts a function with signature
+``(param, func, *args, **kw)`` into a one-parameter family
+of decorators. 
+
+.. code-block:: python
+
+ >>> trace_factory # doctest: +ELLIPSIS
+ 
+
+ >>> trace = trace_factory('Calling %(name)s with args %(args)s '
+ ...                        'and keywords %(kw)s')
+
+In this example the parameter (``message_template``) is 
+just a string, but in general it can be a tuple, a dictionary, or
+a generic object, so there is no real restriction (for instance,
+if you want to define a two-parameter family of decorators just
+use a tuple with two arguments as parameter).
+Here is an example of usage:
+
+.. code-block:: python
+
+ >>> @trace
+ ... def func(): pass
+
+ >>> func()
+ Calling func with args () and keywords {}
 
 ``blocking``
 -------------------------------------------
 
 Sometimes one has to deal with blocking resources, such as ``stdin``, and
 sometimes it is best to have back a "busy" message than to block everything. 
-This behavior can be implemented with a suitable decorator:
+This behavior can be implemented with a suitable family of decorators,
+where the parameter is the busy message:
 
 $$blocking
-
-(notice that without the help of ``decorator``, an additional level of 
-nesting would have been needed). This is actually an example
-of a one-parameter family of decorators.
    
 Functions decorated with ``blocking`` will return a busy message if
 the resource is unavailable, and the intended result if the resource is 
@@ -387,13 +424,13 @@ be locked. Here is a minimalistic example:
 Each call to ``write`` will create a new writer thread, but there will 
 be no synchronization problems since ``write`` is locked.
 
->>> write("data1") 
-
+>>> write("data1") # doctest: +ELLIPSIS
+
 
 >>> time.sleep(.1) # wait a bit, so we are sure data2 is written after data1
 
->>> write("data2") 
-
+>>> write("data2") # doctest: +ELLIPSIS
+
 
 >>> time.sleep(2) # wait for the writers to complete
 
@@ -409,48 +446,24 @@ a ``FunctionMaker`` class which is able to generate on the fly
 functions with a given name and signature from a function template
 passed as a string. Generally speaking, you should not need to
 resort to ``FunctionMaker`` when writing ordinary decorators, but
-it is handy in some circumstances. We will see an example in two
-paragraphs, when implementing a custom decorator factory
-(``decorator_apply``).
-
-Notice that while I do not have plans
-to change or remove the functionality provided in the
-``FunctionMaker`` class, I do not guarantee that it will stay
-unchanged forever. For instance, right now I am using the traditional
-string interpolation syntax for function templates, but Python 2.6
-and Python 3.0 provide a newer interpolation syntax and I may use
-the new syntax in the future.
-On the other hand, the functionality provided by
-``decorator`` has been there from version 0.1 and it is guaranteed to
-stay there forever.
+it is handy in some circumstances. You will see an example shortly, in
+the implementation of a cool decorator utility (``decorator_apply``).
 
-``FunctionMaker`` takes the name and the signature (as a string) of a
-function in input, or a whole function. Then, it creates a new
-function (actually a closure) from a function template (the function
-template must begin with ``def`` with no comments before and you cannot
-use a ``lambda``) via its
-``.make`` method: the name and the signature of the resulting function
-are determinated by the specified name and signature.  For instance,
-here is an example of how to restrict the signature of a function:
+``FunctionMaker`` provides a ``.create`` classmethod which
+takes as input the name, signature, and body of the function
+we want to generate as well as the execution environment
+were the function is generated by ``exec``. Here is an example:
 
 .. code-block:: python
 
  >>> def f(*args, **kw): # a function with a generic signature
  ...     print args, kw
 
- >>> fun = FunctionMaker(name="f1", signature="a,b")
- >>> f1 = fun.make('''\
- ... def %(name)s(%(signature)s):
- ...     f(%(signature)s)''', dict(f=f))
- ...
+ >>> f1 = FunctionMaker.create('f1(a, b)', 'f(a, b)', dict(f=f))
  >>> f1(1,2)
  (1, 2) {}
 
-The dictionary passed in this example (``dict(f=f)``) is the
-execution environment: ``FunctionMaker.make`` actually returns a
-closure, and the original function ``f`` is a variable in the
-closure environment.
-``FunctionMaker.make`` also accepts keyword arguments and such
+``FunctionMaker.create`` also accepts keyword arguments and such
 arguments are attached to the resulting function. This is useful
 if you want to set some function attributes, for instance the
 docstring ``__doc__``.
@@ -462,19 +475,28 @@ be added to the decorated function:
 
 .. code-block:: python
 
- >>> f1 = fun.make('''\
- ... def %(name)s(%(signature)s):
- ...     f(%(signature)s)''', dict(f=f), addsource=True)
- ...
+ >>> f1 = FunctionMaker.create(
+ ...     'f1(a, b)', 'f(a, b)', dict(f=f), addsource=True)
  >>> print f1.__source__
- def f1(a,b):
-     f(a,b)
+ def f1(a, b):
+     f(a, b)
  
 
+Notice that while I do not have plans
+to change or remove the functionality provided in the
+``FunctionMaker`` class, I do not guarantee that it will stay
+unchanged forever. For instance, right now I am using the traditional
+string interpolation syntax for function templates, but Python 2.6
+and Python 3.0 provide a newer interpolation syntax and I may use
+the new syntax in the future.
+On the other hand, the functionality provided by
+``decorator`` has been there from version 0.1 and it is guaranteed to
+stay there forever.
+
 Getting the source code
 ---------------------------------------------------
 
-Internally ``FunctionMaker.make`` uses ``exec`` to generate the
+Internally ``FunctionMaker.create`` uses ``exec`` to generate the
 decorated function. Therefore
 ``inspect.getsource`` will not work for decorated functions. That
 means that the usual '??' trick in IPython will give you the (right on
@@ -647,9 +669,10 @@ would require to change the CPython implementation of functions and
 add an hook to make it possible to change their signature directly. 
 That could happen in future versions of Python (see PEP 362_) and 
 then the decorator module would become obsolete. However, at present,
-even in Python 3.0 it is impossible to change the function signature
+even in Python 3.1 it is impossible to change the function signature
 directly, therefore the ``decorator`` module is still useful.
-Actually, this is one of the main reasons why I am releasing version 3.0.
+Actually, this is one of the main reasons why I keep maintaining
+the module and releasing new versions.
 
 .. _362: http://www.python.org/dev/peps/pep-0362
 
@@ -747,6 +770,9 @@ Finally ``decorator`` cannot be used as a class decorator and the
 `functionality introduced in version 2.3`_ has been removed. That
 means that in order to define decorator factories with classes you
 need to define the ``__call__`` method explicitly (no magic anymore).
+Starting from version 3.1 there is
+an easy way to define decorator factories by using ``decorator.factory``,
+so that there is less need to use classes to implement decorator factories.
 
 All these changes should not cause any trouble, since they were
 all rarely used features. Should you have any trouble, you can always
@@ -756,10 +782,9 @@ The examples shown here have been tested with Python 2.5. Python 2.4
 is also supported - of course the examples requiring the ``with``
 statement will not work there. Python 2.6 works fine, but if you
 run the examples here in the interactive interpreter
-you will notice a couple of minor differences since
+you will notice a few differences since
 ``getargspec`` returns an ``ArgSpec`` namedtuple instead of a regular
-tuple, and the string representation of a thread object returns a
-thread identifier number. That means that running the file
+tuple. That means that running the file
 ``documentation.py`` under Python 2.5 will a few errors, but
 they are not serious. Python 3.0 is kind of supported too.
 Simply run the script ``2to3`` on the module
@@ -818,11 +843,13 @@ today = time.strftime('%Y-%m-%d')
 __doc__ = __doc__.replace('$VERSION', VERSION).replace('$DATE', today)
 
 def decorator_apply(dec, func):
-    "Decorate a function using a signature-non-preserving decorator"
-    fun = FunctionMaker(func)
-    src = '''def %(name)s(%(signature)s):
-    return decorated(%(signature)s)'''
-    return fun.make(src, dict(decorated=dec(func)), undecorated=func)
+    """
+    Decorate a function by preserving the signature even if dec 
+    is not a signature-preserving decorator.
+    """
+    return FunctionMaker.create(
+        func, 'return decorated(%(signature)s)',
+        dict(decorated=dec(func)), undecorated=func)
 
 def _trace(f, *args, **kw):
     print "calling %s with args %s, %s" % (f.__name__, args, kw)
@@ -917,20 +944,19 @@ def _memoize(func, *args, **kw):
 def memoize(f):
     f.cache = {}
     return decorator(_memoize, f)
-
-def blocking(not_avail="Not Available"):
-    def _blocking(f, *args, **kw):
-        if not hasattr(f, "thread"): # no thread running
-            def set_result(): f.result = f(*args, **kw)
-            f.thread = threading.Thread(None, set_result)
-            f.thread.start()
-            return not_avail
-        elif f.thread.isAlive():
-            return not_avail
-        else: # the thread is ended, return the stored result
-            del f.thread 
-            return f.result
-    return decorator(_blocking)
+    
+@decorator.factory
+def blocking(not_avail, f, *args, **kw):
+    if not hasattr(f, "thread"): # no thread running
+        def set_result(): f.result = f(*args, **kw)
+        f.thread = threading.Thread(None, set_result)
+        f.thread.start()
+        return not_avail
+    elif f.thread.isAlive():
+        return not_avail
+    else: # the thread is ended, return the stored result
+        del f.thread
+        return f.result
 
 class User(object):
     "Will just be able to see a page"
diff --git a/setup.py b/setup.py
index 83e990d..67d18e2 100644
--- a/setup.py
+++ b/setup.py
@@ -3,7 +3,7 @@ try:
 except ImportError:
     from distutils.core import setup
 
-VERSION = '3.0.1'
+VERSION = '3.1.0'
 
 if __name__ == '__main__':
     try:
-- 
cgit v1.2.1


From 6d339b7e99dadefd1cd7b8a83e0bb322e15d6796 Mon Sep 17 00:00:00 2001
From: "michele.simionato" 
Date: Sun, 16 Aug 2009 15:39:35 +0000
Subject: Decorator 3.1 (really!)

---
 decorator.py     | 17 +++++--------
 documentation.py | 75 +++++++++++++++++++++++++++++---------------------------
 2 files changed, 45 insertions(+), 47 deletions(-)

diff --git a/decorator.py b/decorator.py
index 2a5c090..79c320d 100755
--- a/decorator.py
+++ b/decorator.py
@@ -34,12 +34,13 @@ import os, sys, re, inspect, warnings
 try:
     from functools import partial
 except ImportError: # for Python version < 2.5
-    def partial(func, *args):
+    class partial(object):
         "A poor man replacement of partial for use in the decorator module only"
-        f = lambda *otherargs: func(*(args + otherargs))
-        f.args = args
-        f.func = func
-        return f
+        def __init__(self, func, *args):
+            self.func = func
+            self.args = args
+        def __call__(self, *otherargs):
+            return self.func(*(self.args + otherargs))
 
 DEF = re.compile('\s*def\s*([_\w][_\w\d]*)\s*\(')
 
@@ -152,12 +153,6 @@ def decorator(caller, func=None):
     else: # returns a decorator
         return partial(decorator, caller)
 
-def decorator_factory(decfac):
-    "decorator.factory(decfac) returns a one-parameter family of decorators"
-    return partial(lambda df, param: decorator(partial(df, param)), decfac)
-
-decorator.factory = decorator_factory
-
 ###################### deprecated functionality #########################
 
 @decorator
diff --git a/documentation.py b/documentation.py
index 2452333..0005d9c 100644
--- a/documentation.py
+++ b/documentation.py
@@ -295,25 +295,28 @@ Here is an example of usage:
 
 If you are using an old Python version (Python 2.4) the
 ``decorator`` module provides a poor man replacement for
-``functools.partial`` as a higher order function.
+``functools.partial``.
 
 There is also an easy way to create one-parameter factories of
-decorators. Suppose for instance you want to generated different
+decorators, based on the following
+``decorator_factory`` utility:
+
+$$decorator_factory
+
+``decorator_factory`` converts a function with signature
+``(param, func, *args, **kw)`` into a one-parameter family
+of decorators. Suppose for instance you want to generated different
 tracing generator, with different tracing messages.
 Here is how to do it:
 
 .. code-block:: python
 
- >>> @decorator.factory
+ >>> @decorator_factory
  ... def trace_factory(message_template, f, *args, **kw):
  ...     name = f.func_name
  ...     print message_template % locals()
  ...     return f(*args, **kw)
 
-``decorator.factory`` converts a function with signature
-``(param, func, *args, **kw)`` into a one-parameter family
-of decorators. 
-
 .. code-block:: python
 
  >>> trace_factory # doctest: +ELLIPSIS
@@ -770,9 +773,9 @@ Finally ``decorator`` cannot be used as a class decorator and the
 `functionality introduced in version 2.3`_ has been removed. That
 means that in order to define decorator factories with classes you
 need to define the ``__call__`` method explicitly (no magic anymore).
-Starting from version 3.1 there is
-an easy way to define decorator factories by using ``decorator.factory``,
-so that there is less need to use classes to implement decorator factories.
+Since there is
+an easy way to define decorator factories by using ``decorator_factory``,
+there is less need to use classes to implement decorator factories.
 
 All these changes should not cause any trouble, since they were
 all rarely used features. Should you have any trouble, you can always
@@ -834,7 +837,7 @@ you are unhappy with it, send me a patch!
 """
 from __future__ import with_statement
 import sys, threading, time, functools, inspect, itertools  
-import multiprocessing
+from functools import partial
 from decorator import *
 from setup import VERSION
 
@@ -842,6 +845,10 @@ today = time.strftime('%Y-%m-%d')
 
 __doc__ = __doc__.replace('$VERSION', VERSION).replace('$DATE', today)
 
+def decorator_factory(decfac): # partial is functools.partial
+    "decorator_factory(decfac) returns a one-parameter family of decorators"
+    return partial(lambda df, param: decorator(partial(df, param)), decfac)
+
 def decorator_apply(dec, func):
     """
     Decorate a function by preserving the signature even if dec 
@@ -945,7 +952,7 @@ def memoize(f):
     f.cache = {}
     return decorator(_memoize, f)
     
-@decorator.factory
+@decorator_factory
 def blocking(not_avail, f, *args, **kw):
     if not hasattr(f, "thread"): # no thread running
         def set_result(): f.result = f(*args, **kw)
@@ -973,40 +980,36 @@ def get_userclass():
 class PermissionError(Exception):
     pass
 
-class Restricted(object):
-    """
-    Restrict public methods and functions to a given class of users.
-    If instantiated twice with the same userclass return the same
-    object.
-    """
-    _cache = {} 
-    def __new__(cls, userclass):
-        if userclass in cls._cache:
-            return cls._cache[userclass]
-        self = cls._cache[userclass] = super(Restricted, cls).__new__(cls)
-        self.userclass = userclass
-        return self
-    def call(self, func, *args, **kw):
-        userclass = get_userclass()
-        if issubclass(userclass, self.userclass):
-            return func(*args, **kw)
-        else:
-            raise PermissionError(
+@decorator_factory
+def restricted(user_class, func, *args, **kw):
+    "Restrict access to a given class of users"
+    userclass = get_userclass()
+    if issubclass(userclass, user_class):
+        return func(*args, **kw)
+    else:
+        raise PermissionError(
             '%s does not have the permission to run %s!'
             % (userclass.__name__, func.__name__))
-    def __call__(self, func):
-        return decorator(self.call, func)
 
 class Action(object):
-    @Restricted(User)
+    """
+    >>> a = Action()
+    >>> a.view() # ok
+    >>> a.insert() # err
+    Traceback (most recent call last):
+       ...
+    PermissionError: User does not have the permission to run insert!
+
+    """
+    @restricted(User)
     def view(self):
         pass
 
-    @Restricted(PowerUser)
+    @restricted(PowerUser)
     def insert(self):
         pass
 
-    @Restricted(Admin)
+    @restricted(Admin)
     def delete(self):
         pass
 
-- 
cgit v1.2.1


From 77098cfb3225adecffde1e76b147e9f7757ddd0c Mon Sep 17 00:00:00 2001
From: "michele.simionato" 
Date: Mon, 17 Aug 2009 05:18:56 +0000
Subject: Fixed a newline bug

---
 decorator.py | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/decorator.py b/decorator.py
index 79c320d..780c13a 100755
--- a/decorator.py
+++ b/decorator.py
@@ -137,7 +137,7 @@ class FunctionMaker(object):
             signature = None
             func = obj
         fun = cls(func, name, signature, defaults)
-        ibody = ''.join('    ' + line for line in body.splitlines())
+        ibody = '\n'.join('    ' + line for line in body.splitlines())
         return fun.make('def %(name)s(%(signature)s):\n' + ibody, 
                         evaldict, addsource, **attrs)
   
-- 
cgit v1.2.1


From c8708c4276a7a06470226c85863ac958b574fcd8 Mon Sep 17 00:00:00 2001
From: "michele.simionato" 
Date: Tue, 18 Aug 2009 04:14:35 +0000
Subject: Decorator 3.1.1

---
 CHANGES.txt      |  2 ++
 decorator.py     | 25 ++++++++++++++++++-------
 documentation.py | 13 +++++++++++--
 setup.py         |  2 +-
 4 files changed, 32 insertions(+), 10 deletions(-)

diff --git a/CHANGES.txt b/CHANGES.txt
index 00ccdef..3dfed71 100755
--- a/CHANGES.txt
+++ b/CHANGES.txt
@@ -1,6 +1,8 @@
 HISTORY
 ----------
 
+3.1.1. Fixed a bug which was breaking Pylons, signaled by
+     Gabriel de Perthuis, and added a test for it. (18/08/2009)
 3.1. Added decorator.factory, an easy way to define families of decorators
      (requested by various users, including David Laban). Refactored the
      FunctionMaker class and added an easier to use .create classmethod.
diff --git a/decorator.py b/decorator.py
index 780c13a..5c81350 100755
--- a/decorator.py
+++ b/decorator.py
@@ -28,19 +28,23 @@ Decorator module, see http://pypi.python.org/pypi/decorator
 for the documentation.
 """
 
-__all__ = ["decorator", "FunctionMaker", "deprecated", "getinfo", "new_wrapper"]
+__all__ = ["decorator", "FunctionMaker", "partial",
+           "deprecated", "getinfo", "new_wrapper"]
 
 import os, sys, re, inspect, warnings
 try:
     from functools import partial
 except ImportError: # for Python version < 2.5
     class partial(object):
-        "A poor man replacement of partial for use in the decorator module only"
-        def __init__(self, func, *args):
+        "A simple replacement of functools.partial"
+        def __init__(self, func, *args, **kw):
             self.func = func
-            self.args = args
-        def __call__(self, *otherargs):
-            return self.func(*(self.args + otherargs))
+            self.args = args                
+            self.keywords = kw
+        def __call__(self, *otherargs, **otherkw):
+            kw = self.keywords.copy()
+            kw.update(otherkw)
+            return self.func(*(self.args + otherargs), **kw)
 
 DEF = re.compile('\s*def\s*([_\w][_\w\d]*)\s*\(')
 
@@ -151,7 +155,14 @@ def decorator(caller, func=None):
             func, "return _call_(_func_, %(signature)s)",
             dict(_call_=caller, _func_=func), undecorated=func)
     else: # returns a decorator
-        return partial(decorator, caller)
+        if isinstance(caller, partial):
+            return partial(decorator, caller)
+        # otherwise assume caller is a function
+        f = inspect.getargspec(caller)[0][0] # first arg
+        return FunctionMaker.create(
+            '%s(%s)' % (caller.__name__, f), 
+            'return decorator(_call_, %s)' % f,
+            dict(_call_=caller, decorator=decorator), undecorated=caller)
 
 ###################### deprecated functionality #########################
 
diff --git a/documentation.py b/documentation.py
index 0005d9c..192ebfb 100644
--- a/documentation.py
+++ b/documentation.py
@@ -281,7 +281,7 @@ object which can be used as a decorator:
 .. code-block:: python
 
  >>> trace # doctest: +ELLIPSIS
- 
+ 
 
 Here is an example of usage:
 
@@ -837,8 +837,8 @@ you are unhappy with it, send me a patch!
 """
 from __future__ import with_statement
 import sys, threading, time, functools, inspect, itertools  
-from functools import partial
 from decorator import *
+from functools import partial
 from setup import VERSION
 
 today = time.strftime('%Y-%m-%d')
@@ -1056,5 +1056,14 @@ def fact(n): # this is not tail-recursive
     if n == 0: return 1
     return n * fact(n-1)
 
+
+def atest_for_pylons():
+    """
+    In version 3.1.0 decorator(caller) returned a nameless partial
+    object, thus breaking Pylons. That must not happen anymore.
+    >>> decorator(_memoize).__name__
+    '_memoize'
+    """
+
 if __name__ == '__main__':
     import doctest; doctest.testmod()
diff --git a/setup.py b/setup.py
index 67d18e2..b406954 100644
--- a/setup.py
+++ b/setup.py
@@ -3,7 +3,7 @@ try:
 except ImportError:
     from distutils.core import setup
 
-VERSION = '3.1.0'
+VERSION = '3.1.1'
 
 if __name__ == '__main__':
     try:
-- 
cgit v1.2.1


From 1182961a2b82500a00f948437fa7f8736537c521 Mon Sep 17 00:00:00 2001
From: "michele.simionato" 
Date: Wed, 26 Aug 2009 05:46:33 +0000
Subject: Release 3.1.2

---
 CHANGES.txt      |  3 +++
 Makefile         |  4 ++--
 decorator.py     | 23 ++++++++++++++---------
 documentation.py | 35 +++++++++++++++++++++++++++++++----
 setup.py         |  2 +-
 5 files changed, 51 insertions(+), 16 deletions(-)

diff --git a/CHANGES.txt b/CHANGES.txt
index 3dfed71..0827995 100755
--- a/CHANGES.txt
+++ b/CHANGES.txt
@@ -1,6 +1,9 @@
 HISTORY
 ----------
 
+3.1.2. Added attributes args, varargs, keywords and arg0, ..., argN
+     to FunctionMaker objects generated from a function; fixed another
+     Pylons-breaking bug signaled by Lawrence Oluyede (25/08/2009)
 3.1.1. Fixed a bug which was breaking Pylons, signaled by
      Gabriel de Perthuis, and added a test for it. (18/08/2009)
 3.1. Added decorator.factory, an easy way to define families of decorators
diff --git a/Makefile b/Makefile
index 35d92a5..12fa499 100644
--- a/Makefile
+++ b/Makefile
@@ -1,7 +1,7 @@
-RST=/home/micheles/trunk/ROnline/RCommon/Python/ms/tools/rst.py
+RST=$(HOME)/trunk/ROnline/RCommon/Python/ms/tools/rst.py
 
 rst: documentation.py
-	python /home/micheles/trunk/ROnline/RCommon/Python/ms/tools/minidoc.py -dH documentation.py
+	python $(HOME)/trunk/ROnline/RCommon/Python/ms/tools/minidoc.py -dH documentation.py
 
 pdf: /tmp/documentation.rst
 	$(RST) -ptd /tmp/documentation.rst; cp /tmp/documentation.pdf /tmp/documentation.html .
diff --git a/decorator.py b/decorator.py
index 5c81350..091d6ff 100755
--- a/decorator.py
+++ b/decorator.py
@@ -31,7 +31,7 @@ for the documentation.
 __all__ = ["decorator", "FunctionMaker", "partial",
            "deprecated", "getinfo", "new_wrapper"]
 
-import os, sys, re, inspect, warnings
+import os, sys, re, inspect, string, warnings
 try:
     from functools import partial
 except ImportError: # for Python version < 2.5
@@ -58,16 +58,19 @@ class FunctionMaker(object):
     def __init__(self, func=None, name=None, signature=None,
                  defaults=None, doc=None, module=None, funcdict=None):
         if func:
-            # func can also be a class or a callable, but not an instance method
+            # func can be a class or a callable, but not an instance method
             self.name = func.__name__
             if self.name == '': # small hack for lambda functions
                 self.name = '_lambda_' 
             self.doc = func.__doc__
             self.module = func.__module__
             if inspect.isfunction(func):
+                argspec = inspect.getargspec(func)
+                self.args, self.varargs, self.keywords, self.defaults = argspec
+                for i, arg in enumerate(self.args):
+                    setattr(self, 'arg%d' % i, arg)
                 self.signature = inspect.formatargspec(
-                    formatvalue=lambda val: "", *inspect.getargspec(func))[1:-1]
-                self.defaults = func.func_defaults
+                    formatvalue=lambda val: "", *argspec)[1:-1]
                 self.dict = func.__dict__.copy()
         if name:
             self.name = name
@@ -95,7 +98,7 @@ class FunctionMaker(object):
         callermodule = sys._getframe(3).f_globals.get('__name__', '?')
         func.__module__ = getattr(self, 'module', callermodule)
         func.__dict__.update(kw)
- 
+
     def make(self, src_templ, evaldict=None, addsource=False, **attrs):
         "Make a new function from a given template and update the signature"
         src = src_templ % vars(self) # expand name and signature
@@ -125,7 +128,8 @@ class FunctionMaker(object):
         return func
 
     @classmethod
-    def create(cls, obj, body, evaldict, defaults=None, addsource=True,**attrs):
+    def create(cls, obj, body, evaldict, defaults=None,
+               doc=None, module=None, addsource=True,**attrs):
         """
         Create a function from the strings name, signature and body.
         evaldict is the evaluation dictionary. If addsource is true an attribute
@@ -134,13 +138,13 @@ class FunctionMaker(object):
         """
         if isinstance(obj, str): # "name(signature)"
             name, rest = obj.strip().split('(', 1)
-            signature = rest[:-1]
+            signature = rest[:-1] #strip a right parens            
             func = None
         else: # a function
             name = None
             signature = None
             func = obj
-        fun = cls(func, name, signature, defaults)
+        fun = cls(func, name, signature, defaults, doc, module)
         ibody = '\n'.join('    ' + line for line in body.splitlines())
         return fun.make('def %(name)s(%(signature)s):\n' + ibody, 
                         evaldict, addsource, **attrs)
@@ -162,7 +166,8 @@ def decorator(caller, func=None):
         return FunctionMaker.create(
             '%s(%s)' % (caller.__name__, f), 
             'return decorator(_call_, %s)' % f,
-            dict(_call_=caller, decorator=decorator), undecorated=caller)
+            dict(_call_=caller, decorator=decorator), undecorated=caller,
+            doc=caller.__doc__, module=caller.__module__)
 
 ###################### deprecated functionality #########################
 
diff --git a/documentation.py b/documentation.py
index 192ebfb..96b3d45 100644
--- a/documentation.py
+++ b/documentation.py
@@ -428,12 +428,12 @@ Each call to ``write`` will create a new writer thread, but there will
 be no synchronization problems since ``write`` is locked.
 
 >>> write("data1") # doctest: +ELLIPSIS
-
+
 
 >>> time.sleep(.1) # wait a bit, so we are sure data2 is written after data1
 
 >>> write("data2") # doctest: +ELLIPSIS
-
+
 
 >>> time.sleep(2) # wait for the writers to complete
 
@@ -466,6 +466,9 @@ were the function is generated by ``exec``. Here is an example:
  >>> f1(1,2)
  (1, 2) {}
 
+It is important to notice that the function body is interpolated
+before being executed, so be careful with the ``%`` sign!
+
 ``FunctionMaker.create`` also accepts keyword arguments and such
 arguments are attached to the resulting function. This is useful
 if you want to set some function attributes, for instance the
@@ -474,7 +477,7 @@ docstring ``__doc__``.
 For debugging/introspection purposes it may be useful to see
 the source code of the generated function; to do that, just
 pass the flag ``addsource=True`` and a ``__source__`` attribute will
-be added to the decorated function:
+be added to the generated function:
 
 .. code-block:: python
 
@@ -485,6 +488,24 @@ be added to the decorated function:
      f(a, b)
  
 
+``FunctionMaker.create`` can take as first argument a string,
+as in the examples before, or a function. This is the most common
+usage, since typically you want to decorate a pre-existing
+function. A framework author may want to use directly ``FunctionMaker.create``
+instead of ``decorator``, since it gives you direct access to the body
+of the generated function. For instance, suppose you want to instrument
+the ``__init__`` methods of a set of classes, by preserving their
+signature (such use case is not made up; this is done in SQAlchemy
+and in other frameworks). When the first argument of ``FunctionMaker.create``
+is a function, a ``FunctionMaker`` object is instantiated internally,
+with attributes ``args``, ``varargs``,
+``keywords`` and ``defaults`` which are the
+the return values of the standard library function ``inspect.getargspec``.
+For each argument in the ``args`` (which is a list of strings containing
+the names of the mandatory arguments) an attribute ``arg0``, ``arg1``,
+..., ``argN`` is also generated. Finally, there is a ``signature`` 
+attribute, a string with the signature of the original function.
+
 Notice that while I do not have plans
 to change or remove the functionality provided in the
 ``FunctionMaker`` class, I do not guarantee that it will stay
@@ -1060,9 +1081,15 @@ def fact(n): # this is not tail-recursive
 def atest_for_pylons():
     """
     In version 3.1.0 decorator(caller) returned a nameless partial
-    object, thus breaking Pylons. That must not happen anymore.
+    object, thus breaking Pylons. That must not happen again.
+
     >>> decorator(_memoize).__name__
     '_memoize'
+
+    Here is another bug of version 3.1.1 to avoid:
+
+    >>> deprecated.__doc__
+    'A decorator for deprecated functions'
     """
 
 if __name__ == '__main__':
diff --git a/setup.py b/setup.py
index b406954..f8dc862 100644
--- a/setup.py
+++ b/setup.py
@@ -3,7 +3,7 @@ try:
 except ImportError:
     from distutils.core import setup
 
-VERSION = '3.1.1'
+VERSION = '3.1.2'
 
 if __name__ == '__main__':
     try:
-- 
cgit v1.2.1


From 4ccf1399ef31e1860b8e89f2d04b4e116ac5889b Mon Sep 17 00:00:00 2001
From: "michele.simionato" 
Date: Thu, 21 Jan 2010 05:56:23 +0000
Subject: Work for decorator version 3.2

---
 CHANGES.txt      |   3 ++
 README.txt       |   4 +-
 decorator.py     |  88 ++--------------------------------------
 documentation.py | 120 ++++++++++++++++++-------------------------------------
 setup.py         |   2 +-
 5 files changed, 48 insertions(+), 169 deletions(-)

diff --git a/CHANGES.txt b/CHANGES.txt
index 0827995..a18d568 100755
--- a/CHANGES.txt
+++ b/CHANGES.txt
@@ -1,6 +1,9 @@
 HISTORY
 ----------
 
+3.2. Added __version__, removed functionality which has been deprecated for
+     more than one year, removed the confusing decorator_factory example
+     from the documentation (21/01/2010)
 3.1.2. Added attributes args, varargs, keywords and arg0, ..., argN
      to FunctionMaker objects generated from a function; fixed another
      Pylons-breaking bug signaled by Lawrence Oluyede (25/08/2009)
diff --git a/README.txt b/README.txt
index b78c600..b6e0b62 100755
--- a/README.txt
+++ b/README.txt
@@ -15,6 +15,6 @@ Run
 
 $ python documentation.py
 
-This should work perfectly with Python 2.4 and Python 2.5 and give
-minor errors with Python 2.6 (some inner details such as the
+This should work perfectly with Python 2.7 and Python 2.6 and give a few
+expected errors with Python 2.5 and 2.4 (some inner details such as the
 introduction of the ArgSpec namedtuple and Thread.__repr__ changed).
diff --git a/decorator.py b/decorator.py
index 091d6ff..7d511fa 100755
--- a/decorator.py
+++ b/decorator.py
@@ -28,8 +28,9 @@ Decorator module, see http://pypi.python.org/pypi/decorator
 for the documentation.
 """
 
-__all__ = ["decorator", "FunctionMaker", "partial",
-           "deprecated", "getinfo", "new_wrapper"]
+__version__ = '3.2.0'
+
+__all__ = ["decorator", "FunctionMaker", "partial"]
 
 import os, sys, re, inspect, string, warnings
 try:
@@ -168,86 +169,3 @@ def decorator(caller, func=None):
             'return decorator(_call_, %s)' % f,
             dict(_call_=caller, decorator=decorator), undecorated=caller,
             doc=caller.__doc__, module=caller.__module__)
-
-###################### deprecated functionality #########################
-
-@decorator
-def deprecated(func, *args, **kw):
-    "A decorator for deprecated functions"
-    warnings.warn(
-        ('Calling the deprecated function %r\n'
-         'Downgrade to decorator 2.3 if you want to use this functionality')
-        % func.__name__, DeprecationWarning, stacklevel=3)
-    return func(*args, **kw)
-
-@deprecated
-def getinfo(func):
-    """
-    Returns an info dictionary containing:
-    - name (the name of the function : str)
-    - argnames (the names of the arguments : list)
-    - defaults (the values of the default arguments : tuple)
-    - signature (the signature : str)
-    - doc (the docstring : str)
-    - module (the module name : str)
-    - dict (the function __dict__ : str)
-    
-    >>> def f(self, x=1, y=2, *args, **kw): pass
-
-    >>> info = getinfo(f)
-
-    >>> info["name"]
-    'f'
-    >>> info["argnames"]
-    ['self', 'x', 'y', 'args', 'kw']
-    
-    >>> info["defaults"]
-    (1, 2)
-
-    >>> info["signature"]
-    'self, x, y, *args, **kw'
-    """
-    assert inspect.ismethod(func) or inspect.isfunction(func)
-    regargs, varargs, varkwargs, defaults = inspect.getargspec(func)
-    argnames = list(regargs)
-    if varargs:
-        argnames.append(varargs)
-    if varkwargs:
-        argnames.append(varkwargs)
-    signature = inspect.formatargspec(regargs, varargs, varkwargs, defaults,
-                                      formatvalue=lambda value: "")[1:-1]
-    return dict(name=func.__name__, argnames=argnames, signature=signature,
-                defaults = func.func_defaults, doc=func.__doc__,
-                module=func.__module__, dict=func.__dict__,
-                globals=func.func_globals, closure=func.func_closure)
-
-@deprecated
-def update_wrapper(wrapper, model, infodict=None):
-    "A replacement for functools.update_wrapper"
-    infodict = infodict or getinfo(model)
-    wrapper.__name__ = infodict['name']
-    wrapper.__doc__ = infodict['doc']
-    wrapper.__module__ = infodict['module']
-    wrapper.__dict__.update(infodict['dict'])
-    wrapper.func_defaults = infodict['defaults']
-    wrapper.undecorated = model
-    return wrapper
-
-@deprecated
-def new_wrapper(wrapper, model):
-    """
-    An improvement over functools.update_wrapper. The wrapper is a generic
-    callable object. It works by generating a copy of the wrapper with the 
-    right signature and by updating the copy, not the original.
-    Moreovoer, 'model' can be a dictionary with keys 'name', 'doc', 'module',
-    'dict', 'defaults'.
-    """
-    if isinstance(model, dict):
-        infodict = model
-    else: # assume model is a function
-        infodict = getinfo(model)
-    assert not '_wrapper_' in infodict["argnames"], (
-        '"_wrapper_" is a reserved argument name!')
-    src = "lambda %(signature)s: _wrapper_(%(signature)s)" % infodict
-    funcopy = eval(src, dict(_wrapper_=wrapper))
-    return update_wrapper(funcopy, model, infodict)
diff --git a/documentation.py b/documentation.py
index 96b3d45..cdd4fae 100644
--- a/documentation.py
+++ b/documentation.py
@@ -119,8 +119,8 @@ keyword arguments:
 .. code-block:: python
 
  >>> from inspect import getargspec 
- >>> print getargspec(f1) 
- ([], 'args', 'kw', None)
+ >>> print getargspec(f1)
+ ArgSpec(args=[], varargs='args', keywords='kw', defaults=None)
 
 This means that introspection tools such as pydoc will give
 wrong informations about the signature of ``f1``. This is pretty bad:
@@ -186,7 +186,7 @@ The signature of ``heavy_computation`` is the one you would expect:
 .. code-block:: python
 
  >>> print getargspec(heavy_computation) 
- ([], None, None, None)
+ ArgSpec(args=[], varargs=None, keywords=None, defaults=None)
 
 A ``trace`` decorator
 ------------------------------------------------------
@@ -219,7 +219,7 @@ and it that it has the correct signature:
 .. code-block:: python
 
  >>> print getargspec(f1) 
- (['x'], None, None, None)
+ ArgSpec(args=['x'], varargs=None, keywords=None, defaults=None)
 
 The same decorator works with functions of any signature:
 
@@ -233,7 +233,7 @@ The same decorator works with functions of any signature:
  calling f with args (0, 3, 2), {}
  
  >>> print getargspec(f) 
- (['x', 'y', 'z'], 'args', 'kw', (1, 2))
+ ArgSpec(args=['x', 'y', 'z'], varargs='args', keywords='kw', defaults=(1, 2))
 
 That includes even functions with exotic signatures like the following:
 
@@ -243,7 +243,7 @@ That includes even functions with exotic signatures like the following:
  ... def exotic_signature((x, y)=(1,2)): return x+y
  
  >>> print getargspec(exotic_signature)
- ([['x', 'y']], None, None, ((1, 2),))
+ ArgSpec(args=[['x', 'y']], varargs=None, keywords=None, defaults=((1, 2),))
  >>> exotic_signature() 
  calling exotic_signature with args ((1, 2),), {}
  3
@@ -297,49 +297,6 @@ If you are using an old Python version (Python 2.4) the
 ``decorator`` module provides a poor man replacement for
 ``functools.partial``.
 
-There is also an easy way to create one-parameter factories of
-decorators, based on the following
-``decorator_factory`` utility:
-
-$$decorator_factory
-
-``decorator_factory`` converts a function with signature
-``(param, func, *args, **kw)`` into a one-parameter family
-of decorators. Suppose for instance you want to generated different
-tracing generator, with different tracing messages.
-Here is how to do it:
-
-.. code-block:: python
-
- >>> @decorator_factory
- ... def trace_factory(message_template, f, *args, **kw):
- ...     name = f.func_name
- ...     print message_template % locals()
- ...     return f(*args, **kw)
-
-.. code-block:: python
-
- >>> trace_factory # doctest: +ELLIPSIS
- 
-
- >>> trace = trace_factory('Calling %(name)s with args %(args)s '
- ...                        'and keywords %(kw)s')
-
-In this example the parameter (``message_template``) is 
-just a string, but in general it can be a tuple, a dictionary, or
-a generic object, so there is no real restriction (for instance,
-if you want to define a two-parameter family of decorators just
-use a tuple with two arguments as parameter).
-Here is an example of usage:
-
-.. code-block:: python
-
- >>> @trace
- ... def func(): pass
-
- >>> func()
- Calling func with args () and keywords {}
-
 ``blocking``
 -------------------------------------------
 
@@ -794,10 +751,6 @@ Finally ``decorator`` cannot be used as a class decorator and the
 `functionality introduced in version 2.3`_ has been removed. That
 means that in order to define decorator factories with classes you
 need to define the ``__call__`` method explicitly (no magic anymore).
-Since there is
-an easy way to define decorator factories by using ``decorator_factory``,
-there is less need to use classes to implement decorator factories.
-
 All these changes should not cause any trouble, since they were
 all rarely used features. Should you have any trouble, you can always
 downgrade to the 2.3 version.
@@ -866,10 +819,6 @@ today = time.strftime('%Y-%m-%d')
 
 __doc__ = __doc__.replace('$VERSION', VERSION).replace('$DATE', today)
 
-def decorator_factory(decfac): # partial is functools.partial
-    "decorator_factory(decfac) returns a one-parameter family of decorators"
-    return partial(lambda df, param: decorator(partial(df, param)), decfac)
-
 def decorator_apply(dec, func):
     """
     Decorate a function by preserving the signature even if dec 
@@ -972,19 +921,20 @@ def _memoize(func, *args, **kw):
 def memoize(f):
     f.cache = {}
     return decorator(_memoize, f)
-    
-@decorator_factory
-def blocking(not_avail, f, *args, **kw):
-    if not hasattr(f, "thread"): # no thread running
-        def set_result(): f.result = f(*args, **kw)
-        f.thread = threading.Thread(None, set_result)
-        f.thread.start()
-        return not_avail
-    elif f.thread.isAlive():
-        return not_avail
-    else: # the thread is ended, return the stored result
-        del f.thread
-        return f.result
+
+def blocking(not_avail):
+    def blocking(f, *args, **kw):
+        if not hasattr(f, "thread"): # no thread running
+            def set_result(): f.result = f(*args, **kw)
+            f.thread = threading.Thread(None, set_result)
+            f.thread.start()
+            return not_avail
+        elif f.thread.isAlive():
+            return not_avail
+        else: # the thread is ended, return the stored result
+            del f.thread
+            return f.result
+    return decorator(blocking)
 
 class User(object):
     "Will just be able to see a page"
@@ -1001,16 +951,17 @@ def get_userclass():
 class PermissionError(Exception):
     pass
 
-@decorator_factory
-def restricted(user_class, func, *args, **kw):
-    "Restrict access to a given class of users"
-    userclass = get_userclass()
-    if issubclass(userclass, user_class):
-        return func(*args, **kw)
-    else:
-        raise PermissionError(
-            '%s does not have the permission to run %s!'
-            % (userclass.__name__, func.__name__))
+def restricted(user_class):
+    def restricted(func, *args, **kw):
+        "Restrict access to a given class of users"
+        userclass = get_userclass()
+        if issubclass(userclass, user_class):
+            return func(*args, **kw)
+        else:
+            raise PermissionError(
+                '%s does not have the permission to run %s!'
+                % (userclass.__name__, func.__name__))
+    return decorator(restricted)
 
 class Action(object):
     """
@@ -1077,7 +1028,6 @@ def fact(n): # this is not tail-recursive
     if n == 0: return 1
     return n * fact(n-1)
 
-
 def atest_for_pylons():
     """
     In version 3.1.0 decorator(caller) returned a nameless partial
@@ -1092,5 +1042,13 @@ def atest_for_pylons():
     'A decorator for deprecated functions'
     """
 
+@decorator
+def deprecated(func, *args, **kw):
+    "A decorator for deprecated functions"
+    warnings.warn(
+        'Calling the deprecated function %r\n' % func.__name__, 
+        DeprecationWarning, stacklevel=3)
+    return func(*args, **kw)
+
 if __name__ == '__main__':
     import doctest; doctest.testmod()
diff --git a/setup.py b/setup.py
index f8dc862..7269d1f 100644
--- a/setup.py
+++ b/setup.py
@@ -3,7 +3,7 @@ try:
 except ImportError:
     from distutils.core import setup
 
-VERSION = '3.1.2'
+from decorator import __version__ as VERSION
 
 if __name__ == '__main__':
     try:
-- 
cgit v1.2.1


From 4452ad10bcf032717f561bc825538e6daecd4c8a Mon Sep 17 00:00:00 2001
From: micheles 
Date: Sun, 28 Mar 2010 17:42:39 +0200
Subject: Recovered my repository

---
 CHANGES.txt  | 0
 README.txt   | 0
 decorator.py | 0
 3 files changed, 0 insertions(+), 0 deletions(-)
 mode change 100755 => 100644 CHANGES.txt
 mode change 100755 => 100644 README.txt
 mode change 100755 => 100644 decorator.py

diff --git a/CHANGES.txt b/CHANGES.txt
old mode 100755
new mode 100644
diff --git a/README.txt b/README.txt
old mode 100755
new mode 100644
diff --git a/decorator.py b/decorator.py
old mode 100755
new mode 100644
-- 
cgit v1.2.1


From 3346499362d111158ae051a2bb17504f01344d58 Mon Sep 17 00:00:00 2001
From: micheles 
Date: Sat, 22 May 2010 09:08:40 +0200
Subject: Version 3.2 of the decorator module

---
 CHANGES.txt         |    7 +-
 MANIFEST.in         |    1 -
 Makefile            |   21 +-
 README.txt          |   27 +-
 decorator.py        |  171 ---------
 documentation.html  | 1013 +++++++++++++++++++++++++++++++++++++++++++++++++++
 documentation.py    |   83 +++--
 documentation3.html |  966 ++++++++++++++++++++++++++++++++++++++++++++++++
 documentation3.py   | 1006 ++++++++++++++++++++++++++++++++++++++++++++++++++
 index.html          |  330 +++++++++++++++++
 performance.sh      |   16 -
 setup.py            |   23 +-
 src/decorator.py    |  172 +++++++++
 13 files changed, 3587 insertions(+), 249 deletions(-)
 delete mode 100644 decorator.py
 create mode 100644 documentation.html
 create mode 100644 documentation3.html
 create mode 100644 documentation3.py
 create mode 100644 index.html
 delete mode 100644 performance.sh
 create mode 100644 src/decorator.py

diff --git a/CHANGES.txt b/CHANGES.txt
index a18d568..4e54d9b 100644
--- a/CHANGES.txt
+++ b/CHANGES.txt
@@ -1,9 +1,10 @@
 HISTORY
 ----------
 
-3.2. Added __version__, removed functionality which has been deprecated for
-     more than one year, removed the confusing decorator_factory example
-     from the documentation (21/01/2010)
+3.2. Added __version__ (thanks to Gregg Lind), removed functionality which 
+     has been deprecated for years, removed the confusing decorator_factory
+     example and added full support for Python 3 (thanks to Claus Klein)
+     (22/05/2010)
 3.1.2. Added attributes args, varargs, keywords and arg0, ..., argN
      to FunctionMaker objects generated from a function; fixed another
      Pylons-breaking bug signaled by Lawrence Oluyede (25/08/2009)
diff --git a/MANIFEST.in b/MANIFEST.in
index 78a2129..5a305de 100644
--- a/MANIFEST.in
+++ b/MANIFEST.in
@@ -1,2 +1 @@
-include documentation.html documentation.pdf
 exclude Makefile
diff --git a/Makefile b/Makefile
index 12fa499..5247dd3 100644
--- a/Makefile
+++ b/Makefile
@@ -1,9 +1,18 @@
-RST=$(HOME)/trunk/ROnline/RCommon/Python/ms/tools/rst.py
+RST=python /home/micheles/trunk/ROnline/RCommon/Python/ms/tools/rst.py
 
-rst: documentation.py
-	python $(HOME)/trunk/ROnline/RCommon/Python/ms/tools/minidoc.py -dH documentation.py
+rst: documentation.py documentation3.py
+	python $(HOME)/trunk/ROnline/RCommon/Python/ms/tools/minidoc.py -d documentation.py
+	python3 $(S)/minidoc3.py -d documentation3.py
 
-pdf: /tmp/documentation.rst
-	$(RST) -ptd /tmp/documentation.rst; cp /tmp/documentation.pdf /tmp/documentation.html .
-upload: documentation.pdf
+html: /tmp/documentation.rst /tmp/documentation3.rst
+	$(RST) /tmp/documentation.rst
+	$(RST) /tmp/documentation3.rst
+	rst2html README.txt index.html
+
+pdf: /tmp/documentation.rst /tmp/documentation3.rst
+	rst2pdf /tmp/documentation.rst -o documentation.pdf
+	rst2pdf /tmp/documentation3.rst -o documentation3.pdf
+	cp /tmp/documentation.html /tmp/documentation3.html .
+
+upload: documentation.pdf documentation3.pdf
 	python setup.py register sdist upload 
diff --git a/README.txt b/README.txt
index b6e0b62..8469081 100644
--- a/README.txt
+++ b/README.txt
@@ -7,14 +7,31 @@ The decorator module requires Python 2.4.
 
 Installation:
 
-Copy the file decorator.py somewhere in your Python path.
+$ python setup.py install
 
 Testing:
 
-Run
+For Python 2.4, 2.5, 2.6, 2.7 run
 
 $ python documentation.py
 
-This should work perfectly with Python 2.7 and Python 2.6 and give a few
-expected errors with Python 2.5 and 2.4 (some inner details such as the
-introduction of the ArgSpec namedtuple and Thread.__repr__ changed).
+for Python 3.X run
+
+$ python documentation3.py
+
+You will see a few innocuous errors with Python 2.4 and 2.5, because
+some inner details such as the introduction of the ArgSpec namedtuple 
+and Thread.__repr__ changed. You may safely ignore them.
+
+Notice:
+
+You may get into trouble if in your system there is an older version
+of the decorator module; in such a case remove the old version.
+
+Documentation:
+
+There are two versions of the documentation, one for `Python 2`_ and one
+for `Python 3`_ .
+
+.. _Python 2: documentation.html
+.. _Python 3: documentation3.html
diff --git a/decorator.py b/decorator.py
deleted file mode 100644
index 7d511fa..0000000
--- a/decorator.py
+++ /dev/null
@@ -1,171 +0,0 @@
-##########################     LICENCE     ###############################
-##
-##   Copyright (c) 2005, Michele Simionato
-##   All rights reserved.
-##
-##   Redistributions of source code must retain the above copyright 
-##   notice, this list of conditions and the following disclaimer.
-##   Redistributions in bytecode form must reproduce the above copyright
-##   notice, this list of conditions and the following disclaimer in
-##   the documentation and/or other materials provided with the
-##   distribution. 
-
-##   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-##   "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-##   LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-##   A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-##   HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
-##   INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
-##   BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
-##   OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
-##   ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
-##   TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
-##   USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
-##   DAMAGE.
-
-"""
-Decorator module, see http://pypi.python.org/pypi/decorator
-for the documentation.
-"""
-
-__version__ = '3.2.0'
-
-__all__ = ["decorator", "FunctionMaker", "partial"]
-
-import os, sys, re, inspect, string, warnings
-try:
-    from functools import partial
-except ImportError: # for Python version < 2.5
-    class partial(object):
-        "A simple replacement of functools.partial"
-        def __init__(self, func, *args, **kw):
-            self.func = func
-            self.args = args                
-            self.keywords = kw
-        def __call__(self, *otherargs, **otherkw):
-            kw = self.keywords.copy()
-            kw.update(otherkw)
-            return self.func(*(self.args + otherargs), **kw)
-
-DEF = re.compile('\s*def\s*([_\w][_\w\d]*)\s*\(')
-
-# basic functionality
-class FunctionMaker(object):
-    """
-    An object with the ability to create functions with a given signature.
-    It has attributes name, doc, module, signature, defaults, dict and
-    methods update and make.
-    """
-    def __init__(self, func=None, name=None, signature=None,
-                 defaults=None, doc=None, module=None, funcdict=None):
-        if func:
-            # func can be a class or a callable, but not an instance method
-            self.name = func.__name__
-            if self.name == '': # small hack for lambda functions
-                self.name = '_lambda_' 
-            self.doc = func.__doc__
-            self.module = func.__module__
-            if inspect.isfunction(func):
-                argspec = inspect.getargspec(func)
-                self.args, self.varargs, self.keywords, self.defaults = argspec
-                for i, arg in enumerate(self.args):
-                    setattr(self, 'arg%d' % i, arg)
-                self.signature = inspect.formatargspec(
-                    formatvalue=lambda val: "", *argspec)[1:-1]
-                self.dict = func.__dict__.copy()
-        if name:
-            self.name = name
-        if signature is not None:
-            self.signature = signature
-        if defaults:
-            self.defaults = defaults
-        if doc:
-            self.doc = doc
-        if module:
-            self.module = module
-        if funcdict:
-            self.dict = funcdict
-        # check existence required attributes
-        assert hasattr(self, 'name')
-        if not hasattr(self, 'signature'):
-            raise TypeError('You are decorating a non function: %s' % func)
-
-    def update(self, func, **kw):
-        "Update the signature of func with the data in self"
-        func.__name__ = self.name
-        func.__doc__ = getattr(self, 'doc', None)
-        func.__dict__ = getattr(self, 'dict', {})
-        func.func_defaults = getattr(self, 'defaults', ())
-        callermodule = sys._getframe(3).f_globals.get('__name__', '?')
-        func.__module__ = getattr(self, 'module', callermodule)
-        func.__dict__.update(kw)
-
-    def make(self, src_templ, evaldict=None, addsource=False, **attrs):
-        "Make a new function from a given template and update the signature"
-        src = src_templ % vars(self) # expand name and signature
-        evaldict = evaldict or {}
-        mo = DEF.match(src)
-        if mo is None:
-            raise SyntaxError('not a valid function template\n%s' % src)
-        name = mo.group(1) # extract the function name
-        reserved_names = set([name] + [
-            arg.strip(' *') for arg in self.signature.split(',')])
-        for n, v in evaldict.iteritems():
-            if n in reserved_names:
-                raise NameError('%s is overridden in\n%s' % (n, src))
-        if not src.endswith('\n'): # add a newline just for safety
-            src += '\n'
-        try:
-            code = compile(src, '', 'single')
-            exec code in evaldict
-        except:
-            print >> sys.stderr, 'Error in generated code:'
-            print >> sys.stderr, src
-            raise
-        func = evaldict[name]
-        if addsource:
-            attrs['__source__'] = src
-        self.update(func, **attrs)
-        return func
-
-    @classmethod
-    def create(cls, obj, body, evaldict, defaults=None,
-               doc=None, module=None, addsource=True,**attrs):
-        """
-        Create a function from the strings name, signature and body.
-        evaldict is the evaluation dictionary. If addsource is true an attribute
-        __source__ is added to the result. The attributes attrs are added,
-        if any.
-        """
-        if isinstance(obj, str): # "name(signature)"
-            name, rest = obj.strip().split('(', 1)
-            signature = rest[:-1] #strip a right parens            
-            func = None
-        else: # a function
-            name = None
-            signature = None
-            func = obj
-        fun = cls(func, name, signature, defaults, doc, module)
-        ibody = '\n'.join('    ' + line for line in body.splitlines())
-        return fun.make('def %(name)s(%(signature)s):\n' + ibody, 
-                        evaldict, addsource, **attrs)
-  
-def decorator(caller, func=None):
-    """
-    decorator(caller) converts a caller function into a decorator;
-    decorator(caller, func) decorates a function using a caller.
-    """
-    if func is not None: # returns a decorated function
-        return FunctionMaker.create(
-            func, "return _call_(_func_, %(signature)s)",
-            dict(_call_=caller, _func_=func), undecorated=func)
-    else: # returns a decorator
-        if isinstance(caller, partial):
-            return partial(decorator, caller)
-        # otherwise assume caller is a function
-        f = inspect.getargspec(caller)[0][0] # first arg
-        return FunctionMaker.create(
-            '%s(%s)' % (caller.__name__, f), 
-            'return decorator(_call_, %s)' % f,
-            dict(_call_=caller, decorator=decorator), undecorated=caller,
-            doc=caller.__doc__, module=caller.__module__)
diff --git a/documentation.html b/documentation.html
new file mode 100644
index 0000000..2bca550
--- /dev/null
+++ b/documentation.html
@@ -0,0 +1,1013 @@
+
+
+
+
+
+
+The decorator module
+
+
+
+
+
+

The decorator module

+ +++ + + + + + + + + + + + + + + + +
Author:Michele Simionato
E-mail:michele.simionato@gmail.com
Version:3.2.0 (2010-05-22)
Requires:Python 2.4+
Download page:http://pypi.python.org/pypi/decorator/3.2.0
Installation:easy_install decorator
License:BSD license
+ +
+

Introduction

+

Python decorators are an interesting example of why syntactic sugar +matters. In principle, their introduction in Python 2.4 changed +nothing, since they do not provide any new functionality which was not +already present in the language. In practice, their introduction has +significantly changed the way we structure our programs in Python. I +believe the change is for the best, and that decorators are a great +idea since:

+
    +
  • decorators help reducing boilerplate code;
  • +
  • decorators help separation of concerns;
  • +
  • decorators enhance readability and maintenability;
  • +
  • decorators are explicit.
  • +
+

Still, as of now, writing custom decorators correctly requires +some experience and it is not as easy as it could be. For instance, +typical implementations of decorators involve nested functions, and +we all know that flat is better than nested.

+

The aim of the decorator module it to simplify the usage of +decorators for the average programmer, and to popularize decorators by +showing various non-trivial examples. Of course, as all techniques, +decorators can be abused (I have seen that) and you should not try to +solve every problem with a decorator, just because you can.

+

You may find the source code for all the examples +discussed here in the documentation.py file, which contains +this documentation in the form of doctests.

+
+
+

Definitions

+

Technically speaking, any Python object which can be called with one argument +can be used as a decorator. However, this definition is somewhat too large +to be really useful. It is more convenient to split the generic class of +decorators in two subclasses:

+
    +
  • signature-preserving decorators, i.e. callable objects taking a +function as input and returning a function with the same +signature as output;
  • +
  • signature-changing decorators, i.e. decorators that change +the signature of their input function, or decorators returning +non-callable objects.
  • +
+

Signature-changing decorators have their use: for instance the +builtin classes staticmethod and classmethod are in this +group, since they take functions and return descriptor objects which +are not functions, nor callables.

+

However, signature-preserving decorators are more common and easier to +reason about; in particular signature-preserving decorators can be +composed together whereas other decorators in general cannot.

+

Writing signature-preserving decorators from scratch is not that +obvious, especially if one wants to define proper decorators that +can accept functions with any signature. A simple example will clarify +the issue.

+
+
+

Statement of the problem

+

A very common use case for decorators is the memoization of functions. +A memoize decorator works by caching +the result of the function call in a dictionary, so that the next time +the function is called with the same input parameters the result is retrieved +from the cache and not recomputed. There are many implementations of +memoize in http://www.python.org/moin/PythonDecoratorLibrary, +but they do not preserve the signature. +A simple implementation for Python 2.5 could be the following (notice +that in general it is impossible to memoize correctly something +that depends on non-hashable arguments):

+
+def memoize25(func):
+    func.cache = {}
+    def memoize(*args, **kw):
+        if kw: # frozenset is used to ensure hashability
+            key = args, frozenset(kw.iteritems())
+        else:
+            key = args
+        cache = func.cache
+        if key in cache:
+            return cache[key]
+        else:
+            cache[key] = result = func(*args, **kw)
+            return result
+    return functools.update_wrapper(memoize, func)
+
+

Here we used the functools.update_wrapper utility, which has +been added in Python 2.5 expressly to simplify the definition of decorators +(in older versions of Python you need to copy the function attributes +__name__, __doc__, __module__ and __dict__ +from the original function to the decorated function by hand).

+

The implementation above works in the sense that the decorator +can accept functions with generic signatures; unfortunately this +implementation does not define a signature-preserving decorator, since in +general memoize25 returns a function with a +different signature from the original function.

+

Consider for instance the following case:

+
+
>>> @memoize25
+... def f1(x):
+...     time.sleep(1) # simulate some long computation
+...     return x
+
+ +
+

Here the original function takes a single argument named x, +but the decorated function takes any number of arguments and +keyword arguments:

+
+
>>> from inspect import getargspec
+>>> print getargspec(f1)
+ArgSpec(args=[], varargs='args', keywords='kw', defaults=None)
+
+ +
+

This means that introspection tools such as pydoc will give +wrong informations about the signature of f1. This is pretty bad: +pydoc will tell you that the function accepts a generic signature +*args, **kw, but when you try to call the function with more than an +argument, you will get an error:

+
+
>>> f1(0, 1)
+Traceback (most recent call last):
+   ...
+TypeError: f1() takes exactly 1 argument (2 given)
+
+ +
+
+
+

The solution

+

The solution is to provide a generic factory of generators, which +hides the complexity of making signature-preserving decorators +from the application programmer. The decorator function in +the decorator module is such a factory:

+
+
>>> from decorator import decorator
+
+ +
+

decorator takes two arguments, a caller function describing the +functionality of the decorator and a function to be decorated; it +returns the decorated function. The caller function must have +signature (f, *args, **kw) and it must call the original function f +with arguments args and kw, implementing the wanted capability, +i.e. memoization in this case:

+
+def _memoize(func, *args, **kw):
+    if kw: # frozenset is used to ensure hashability
+        key = args, frozenset(kw.iteritems())
+    else:
+        key = args
+    cache = func.cache # attributed added by memoize
+    if key in cache:
+        return cache[key]
+    else:
+        cache[key] = result = func(*args, **kw)
+        return result
+
+

At this point you can define your decorator as follows:

+
+def memoize(f):
+    f.cache = {}
+    return decorator(_memoize, f)
+
+

The difference with respect to the Python 2.5 approach, which is based +on nested functions, is that the decorator module forces you to lift +the inner function at the outer level (flat is better than nested). +Moreover, you are forced to pass explicitly the function you want to +decorate to the caller function.

+

Here is a test of usage:

+
+
>>> @memoize
+... def heavy_computation():
+...     time.sleep(2)
+...     return "done"
+
+>>> print heavy_computation() # the first time it will take 2 seconds
+done
+
+>>> print heavy_computation() # the second time it will be instantaneous
+done
+
+ +
+

The signature of heavy_computation is the one you would expect:

+
+
>>> print getargspec(heavy_computation)
+ArgSpec(args=[], varargs=None, keywords=None, defaults=None)
+
+ +
+
+
+

A trace decorator

+

As an additional example, here is how you can define a trivial +trace decorator, which prints a message everytime the traced +function is called:

+
+def _trace(f, *args, **kw):
+    print "calling %s with args %s, %s" % (f.__name__, args, kw)
+    return f(*args, **kw)
+
+
+def trace(f):
+    return decorator(_trace, f)
+
+

Here is an example of usage:

+
+
>>> @trace
+... def f1(x):
+...     pass
+
+ +
+

It is immediate to verify that f1 works

+
+
>>> f1(0)
+calling f1 with args (0,), {}
+
+ +
+

and it that it has the correct signature:

+
+
>>> print getargspec(f1)
+ArgSpec(args=['x'], varargs=None, keywords=None, defaults=None)
+
+ +
+

The same decorator works with functions of any signature:

+
+
>>> @trace
+... def f(x, y=1, z=2, *args, **kw):
+...     pass
+
+>>> f(0, 3)
+calling f with args (0, 3, 2), {}
+
+>>> print getargspec(f)
+ArgSpec(args=['x', 'y', 'z'], varargs='args', keywords='kw', defaults=(1, 2))
+
+ +
+

That includes even functions with exotic signatures like the following:

+
+
>>> @trace
+... def exotic_signature((x, y)=(1,2)): return x+y
+
+>>> print getargspec(exotic_signature)
+ArgSpec(args=[['x', 'y']], varargs=None, keywords=None, defaults=((1, 2),))
+>>> exotic_signature()
+calling exotic_signature with args ((1, 2),), {}
+3
+
+ +
+

Notice that the support for exotic signatures has been deprecated +in Python 2.6 and removed in Python 3.0.

+
+
+

decorator is a decorator

+

It may be annoying to write a caller function (like the _trace +function above) and then a trivial wrapper +(def trace(f): return decorator(_trace, f)) every time. For this reason, +the decorator module provides an easy shortcut to convert +the caller function into a signature-preserving decorator: +you can just call decorator with a single argument. +In our example you can just write trace = decorator(_trace). +The decorator function can also be used as a signature-changing +decorator, just as classmethod and staticmethod. +However, classmethod and staticmethod return generic +objects which are not callable, while decorator returns +signature-preserving decorators, i.e. functions of a single argument. +For instance, you can write directly

+
+
>>> @decorator
+... def trace(f, *args, **kw):
+...     print "calling %s with args %s, %s" % (f.func_name, args, kw)
+...     return f(*args, **kw)
+
+ +
+

and now trace will be a decorator. Actually trace is a partial +object which can be used as a decorator:

+
+
>>> trace
+<function trace at 0x...>
+
+ +
+

Here is an example of usage:

+
+
>>> @trace
+... def func(): pass
+
+>>> func()
+calling func with args (), {}
+
+ +
+

If you are using an old Python version (Python 2.4) the +decorator module provides a poor man replacement for +functools.partial.

+
+
+

blocking

+

Sometimes one has to deal with blocking resources, such as stdin, and +sometimes it is best to have back a "busy" message than to block everything. +This behavior can be implemented with a suitable family of decorators, +where the parameter is the busy message:

+
+def blocking(not_avail):
+    def blocking(f, *args, **kw):
+        if not hasattr(f, "thread"): # no thread running
+            def set_result(): f.result = f(*args, **kw)
+            f.thread = threading.Thread(None, set_result)
+            f.thread.start()
+            return not_avail
+        elif f.thread.isAlive():
+            return not_avail
+        else: # the thread is ended, return the stored result
+            del f.thread
+            return f.result
+    return decorator(blocking)
+
+

Functions decorated with blocking will return a busy message if +the resource is unavailable, and the intended result if the resource is +available. For instance:

+
+
>>> @blocking("Please wait ...")
+... def read_data():
+...     time.sleep(3) # simulate a blocking resource
+...     return "some data"
+
+>>> print read_data() # data is not available yet
+Please wait ...
+
+>>> time.sleep(1)
+>>> print read_data() # data is not available yet
+Please wait ...
+
+>>> time.sleep(1)
+>>> print read_data() # data is not available yet
+Please wait ...
+
+>>> time.sleep(1.1) # after 3.1 seconds, data is available
+>>> print read_data()
+some data
+
+ +
+
+
+

async

+

We have just seen an examples of a simple decorator factory, +implemented as a function returning a decorator. +For more complex situations, it is more +convenient to implement decorator factories as classes returning +callable objects that can be used as signature-preserving +decorators. The suggested pattern to do that is to introduce +a helper method call(self, func, *args, **kw) and to call +it in the __call__(self, func) method.

+

As an example, here I show a decorator +which is able to convert a blocking function into an asynchronous +function. The function, when called, +is executed in a separate thread. Moreover, it is possible to set +three callbacks on_success, on_failure and on_closing, +to specify how to manage the function call. +The implementation is the following:

+
+def on_success(result): # default implementation
+    "Called on the result of the function"
+    return result
+
+
+def on_failure(exc_info): # default implementation
+    "Called if the function fails"
+    pass
+
+
+def on_closing(): # default implementation
+    "Called at the end, both in case of success and failure"
+    pass
+
+
+class Async(object):
+    """
+    A decorator converting blocking functions into asynchronous
+    functions, by using threads or processes. Examples:
+
+    async_with_threads =  Async(threading.Thread)
+    async_with_processes =  Async(multiprocessing.Process)
+    """
+
+    def __init__(self, threadfactory):
+        self.threadfactory = threadfactory
+
+    def __call__(self, func, on_success=on_success,
+                 on_failure=on_failure, on_closing=on_closing):
+        # every decorated function has its own independent thread counter
+        func.counter = itertools.count(1)
+        func.on_success = on_success
+        func.on_failure = on_failure
+        func.on_closing = on_closing
+        return decorator(self.call, func)
+
+    def call(self, func, *args, **kw):
+        def func_wrapper():
+            try:
+                result = func(*args, **kw)
+            except:
+                func.on_failure(sys.exc_info())
+            else:
+                return func.on_success(result)
+            finally:
+                func.on_closing()
+        name = '%s-%s' % (func.__name__, func.counter.next())
+        thread = self.threadfactory(None, func_wrapper, name)
+        thread.start()
+        return thread
+
+

The decorated function returns +the current execution thread, which can be stored and checked later, for +instance to verify that the thread .isAlive().

+

Here is an example of usage. Suppose one wants to write some data to +an external resource which can be accessed by a single user at once +(for instance a printer). Then the access to the writing function must +be locked. Here is a minimalistic example:

+
+
>>> async = Async(threading.Thread)
+
+>>> datalist = [] # for simplicity the written data are stored into a list.
+
+>>> @async
+... def write(data):
+...     # append data to the datalist by locking
+...     with threading.Lock():
+...         time.sleep(1) # emulate some long running operation
+...         datalist.append(data)
+...     # other operations not requiring a lock here
+
+ +
+

Each call to write will create a new writer thread, but there will +be no synchronization problems since write is locked.

+
+
>>> write("data1")
+<Thread(write-1, started...)>
+
+>>> time.sleep(.1) # wait a bit, so we are sure data2 is written after data1
+
+>>> write("data2")
+<Thread(write-2, started...)>
+
+>>> time.sleep(2) # wait for the writers to complete
+
+>>> print datalist
+['data1', 'data2']
+
+ +
+
+
+

The FunctionMaker class

+

You may wonder about how the functionality of the decorator module +is implemented. The basic building block is +a FunctionMaker class which is able to generate on the fly +functions with a given name and signature from a function template +passed as a string. Generally speaking, you should not need to +resort to FunctionMaker when writing ordinary decorators, but +it is handy in some circumstances. You will see an example shortly, in +the implementation of a cool decorator utility (decorator_apply).

+

FunctionMaker provides a .create classmethod which +takes as input the name, signature, and body of the function +we want to generate as well as the execution environment +were the function is generated by exec. Here is an example:

+
+
>>> def f(*args, **kw): # a function with a generic signature
+...     print args, kw
+
+>>> f1 = FunctionMaker.create('f1(a, b)', 'f(a, b)', dict(f=f))
+>>> f1(1,2)
+(1, 2) {}
+
+ +
+

It is important to notice that the function body is interpolated +before being executed, so be careful with the % sign!

+

FunctionMaker.create also accepts keyword arguments and such +arguments are attached to the resulting function. This is useful +if you want to set some function attributes, for instance the +docstring __doc__.

+

For debugging/introspection purposes it may be useful to see +the source code of the generated function; to do that, just +pass the flag addsource=True and a __source__ attribute will +be added to the generated function:

+
+
>>> f1 = FunctionMaker.create(
+...     'f1(a, b)', 'f(a, b)', dict(f=f), addsource=True)
+>>> print f1.__source__
+def f1(a, b):
+    f(a, b)
+<BLANKLINE>
+
+ +
+

FunctionMaker.create can take as first argument a string, +as in the examples before, or a function. This is the most common +usage, since typically you want to decorate a pre-existing +function. A framework author may want to use directly FunctionMaker.create +instead of decorator, since it gives you direct access to the body +of the generated function. For instance, suppose you want to instrument +the __init__ methods of a set of classes, by preserving their +signature (such use case is not made up; this is done in SQAlchemy +and in other frameworks). When the first argument of FunctionMaker.create +is a function, a FunctionMaker object is instantiated internally, +with attributes args, varargs, +keywords and defaults which are the +the return values of the standard library function inspect.getargspec. +For each argument in the args (which is a list of strings containing +the names of the mandatory arguments) an attribute arg0, arg1, +..., argN is also generated. Finally, there is a signature +attribute, a string with the signature of the original function.

+

Notice that while I do not have plans +to change or remove the functionality provided in the +FunctionMaker class, I do not guarantee that it will stay +unchanged forever. For instance, right now I am using the traditional +string interpolation syntax for function templates, but Python 2.6 +and Python 3.0 provide a newer interpolation syntax and I may use +the new syntax in the future. +On the other hand, the functionality provided by +decorator has been there from version 0.1 and it is guaranteed to +stay there forever.

+
+
+

Getting the source code

+

Internally FunctionMaker.create uses exec to generate the +decorated function. Therefore +inspect.getsource will not work for decorated functions. That +means that the usual '??' trick in IPython will give you the (right on +the spot) message Dynamically generated function. No source code +available. In the past I have considered this acceptable, since +inspect.getsource does not really work even with regular +decorators. In that case inspect.getsource gives you the wrapper +source code which is probably not what you want:

+
+def identity_dec(func):
+    def wrapper(*args, **kw):
+        return func(*args, **kw)
+    return wrapper
+
+
+
@identity_dec
+def example(): pass
+
+>>> print inspect.getsource(example)
+    def wrapper(*args, **kw):
+        return func(*args, **kw)
+<BLANKLINE>
+
+ +
+

(see bug report 1764286 for an explanation of what is happening). +Unfortunately the bug is still there, even in Python 2.6 and 3.0. +There is however a workaround. The decorator module adds an +attribute .undecorated to the decorated function, containing +a reference to the original function. The easy way to get +the source code is to call inspect.getsource on the +undecorated function:

+
+
>>> print inspect.getsource(factorial.undecorated)
+@tail_recursive
+def factorial(n, acc=1):
+    "The good old factorial"
+    if n == 0: return acc
+    return factorial(n-1, n*acc)
+<BLANKLINE>
+
+ +
+
+
+

Dealing with third party decorators

+

Sometimes you find on the net some cool decorator that you would +like to include in your code. However, more often than not the cool +decorator is not signature-preserving. Therefore you may want an easy way to +upgrade third party decorators to signature-preserving decorators without +having to rewrite them in terms of decorator. You can use a +FunctionMaker to implement that functionality as follows:

+
+def decorator_apply(dec, func):
+    """
+    Decorate a function by preserving the signature even if dec
+    is not a signature-preserving decorator.
+    """
+    return FunctionMaker.create(
+        func, 'return decorated(%(signature)s)',
+        dict(decorated=dec(func)), undecorated=func)
+
+

decorator_apply sets the attribute .undecorated of the generated +function to the original function, so that you can get the right +source code.

+

Notice that I am not providing this functionality in the decorator +module directly since I think it is best to rewrite the decorator rather +than adding an additional level of indirection. However, practicality +beats purity, so you can add decorator_apply to your toolbox and +use it if you need to.

+

In order to give an example of usage of decorator_apply, I will show a +pretty slick decorator that converts a tail-recursive function in an iterative +function. I have shamelessly stolen the basic idea from Kay Schluehr's recipe +in the Python Cookbook, +http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/496691.

+
+class TailRecursive(object):
+    """
+    tail_recursive decorator based on Kay Schluehr's recipe
+    http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/496691
+    with improvements by me and George Sakkis.
+    """
+
+    def __init__(self, func):
+        self.func = func
+        self.firstcall = True
+        self.CONTINUE = object() # sentinel
+
+    def __call__(self, *args, **kwd):
+        CONTINUE = self.CONTINUE
+        if self.firstcall:
+            func = self.func
+            self.firstcall = False
+            try:
+                while True:
+                    result = func(*args, **kwd)
+                    if result is CONTINUE: # update arguments
+                        args, kwd = self.argskwd
+                    else: # last call
+                        return result
+            finally:
+                self.firstcall = True
+        else: # return the arguments of the tail call
+            self.argskwd = args, kwd
+            return CONTINUE
+
+

Here the decorator is implemented as a class returning callable +objects.

+
+def tail_recursive(func):
+    return decorator_apply(TailRecursive, func)
+
+

Here is how you apply the upgraded decorator to the good old factorial:

+
+@tail_recursive
+def factorial(n, acc=1):
+    "The good old factorial"
+    if n == 0: return acc
+    return factorial(n-1, n*acc)
+
+
+
>>> print factorial(4)
+24
+
+ +
+

This decorator is pretty impressive, and should give you some food for +your mind ;) Notice that there is no recursion limit now, and you can +easily compute factorial(1001) or larger without filling the stack +frame. Notice also that the decorator will not work on functions which +are not tail recursive, such as the following

+
+def fact(n): # this is not tail-recursive
+    if n == 0: return 1
+    return n * fact(n-1)
+
+

(reminder: a function is tail recursive if it either returns a value without +making a recursive call, or returns directly the result of a recursive +call).

+
+
+

Caveats and limitations

+

The first thing you should be aware of, it the fact that decorators +have a performance penalty. +The worse case is shown by the following example:

+
+$ cat performance.sh
+python -m timeit -s "
+from decorator import decorator
+
+@decorator
+def do_nothing(func, *args, **kw):
+    return func(*args, **kw)
+
+@do_nothing
+def f():
+    pass
+" "f()"
+
+python -m timeit -s "
+def f():
+    pass
+" "f()"
+
+

On my MacBook, using the do_nothing decorator instead of the +plain function is more than three times slower:

+
+$ bash performance.sh
+1000000 loops, best of 3: 0.995 usec per loop
+1000000 loops, best of 3: 0.273 usec per loop
+
+

It should be noted that a real life function would probably do +something more useful than f here, and therefore in real life the +performance penalty could be completely negligible. As always, the +only way to know if there is +a penalty in your specific use case is to measure it.

+

You should be aware that decorators will make your tracebacks +longer and more difficult to understand. Consider this example:

+
+
>>> @trace
+... def f():
+...     1/0
+
+ +
+

Calling f() will give you a ZeroDivisionError, but since the +function is decorated the traceback will be longer:

+
+
>>> f()
+Traceback (most recent call last):
+  ...
+     File "<string>", line 2, in f
+     File "<doctest __main__[18]>", line 4, in trace
+       return f(*args, **kw)
+     File "<doctest __main__[47]>", line 3, in f
+       1/0
+ZeroDivisionError: integer division or modulo by zero
+
+ +
+

You see here the inner call to the decorator trace, which calls +f(*args, **kw), and a reference to File "<string>", line 2, in f. +This latter reference is due to the fact that internally the decorator +module uses exec to generate the decorated function. Notice that +exec is not responsibile for the performance penalty, since is the +called only once at function decoration time, and not every time +the decorated function is called.

+

At present, there is no clean way to avoid exec. A clean solution +would require to change the CPython implementation of functions and +add an hook to make it possible to change their signature directly. +That could happen in future versions of Python (see PEP 362) and +then the decorator module would become obsolete. However, at present, +even in Python 3.1 it is impossible to change the function signature +directly, therefore the decorator module is still useful. +Actually, this is one of the main reasons why I keep maintaining +the module and releasing new versions.

+

In the present implementation, decorators generated by decorator +can only be used on user-defined Python functions or methods, not on generic +callable objects, nor on built-in functions, due to limitations of the +inspect module in the standard library. Moreover, notice +that you can decorate a method, but only before if becomes a bound or unbound +method, i.e. inside the class. +Here is an example of valid decoration:

+
+
>>> class C(object):
+...      @trace
+...      def meth(self):
+...          pass
+
+ +
+

Here is an example of invalid decoration, when the decorator in +called too late:

+
+
>>> class C(object):
+...      def meth(self):
+...          pass
+...
+>>> trace(C.meth)
+Traceback (most recent call last):
+  ...
+TypeError: You are decorating a non function: <unbound method C.meth>
+
+ +
+

The solution is to extract the inner function from the unbound method:

+
+
>>> trace(C.meth.im_func)
+<function meth at 0x...>
+
+ +
+

There is a restriction on the names of the arguments: for instance, +if try to call an argument _call_ or _func_ +you will get a NameError:

+
+
>>> @trace
+... def f(_func_): print f
+...
+Traceback (most recent call last):
+  ...
+NameError: _func_ is overridden in
+def f(_func_):
+    return _call_(_func_, _func_)
+
+ +
+

Finally, the implementation is such that the decorated function contains +a copy of the original function dictionary +(vars(decorated_f) is not vars(f)):

+
+
>>> def f(): pass # the original function
+>>> f.attr1 = "something" # setting an attribute
+>>> f.attr2 = "something else" # setting another attribute
+
+>>> traced_f = trace(f) # the decorated function
+
+>>> traced_f.attr1
+'something'
+>>> traced_f.attr2 = "something different" # setting attr
+>>> f.attr2 # the original attribute did not change
+'something else'
+
+ +
+
+
+

Compatibility notes

+

Version 3.2 is the first version of the decorator module to officially +support Python 3.0. Actually, the module has supported Python 3.0 from +the beginning, via the 2to3 conversion tool, but this step has +been now integrated in the build process, thanks to the distribute +project, the Python 3-compatible replacement of easy_install. +The hard work (for me) has been converting the documentation and the +doctests. This has been possibly only now that docutils and pygments +have been ported to Python 3.

+

The decorator module per se does not contain any change, apart +from the removal of the functions get_info and new_wrapper, +which have been deprecated for years. get_info has been removed +since it was little used and since it had to be changed anyway to work +with Python 3.0; new_wrapper has been removed since it was +useless: its major use case (converting signature changing decorators +to signature preserving decorators) has been subsumed by +decorator_apply and the other use case can be managed with the +FunctionMaker.

+

There are a few changes in the documentation: I removed the +decorator_factory example, which was confusing some of my users, +and I removed the part about exotic signatures in the Python 3 +documentation, since Python 3 does not support them. +Notice that there is no support for Python 3 function annotations +since it seems premature at the moment, when most people are +still using Python 2.X.

+

Finally decorator cannot be used as a class decorator and the +functionality introduced in version 2.3 has been removed. That +means that in order to define decorator factories with classes you +need to define the __call__ method explicitly (no magic anymore). +All these changes should not cause any trouble, since they were +all rarely used features. Should you have any trouble, you can always +downgrade to the 2.3 version.

+

The examples shown here have been tested with Python 2.6. Python 2.4 +is also supported - of course the examples requiring the with +statement will not work there. Python 2.5 works fine, but if you +run the examples here in the interactive interpreter +you will notice a few differences since +getargspec returns an ArgSpec namedtuple instead of a regular +tuple. That means that running the file +documentation.py under Python 2.5 will a few errors, but +they are not serious.

+
+
+

LICENCE

+

Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met:

+
+Copyright (c) 2005, Michele Simionato
+All rights reserved.
+
+Redistributions of source code must retain the above copyright
+notice, this list of conditions and the following disclaimer.
+Redistributions in bytecode form must reproduce the above copyright
+notice, this list of conditions and the following disclaimer in
+the documentation and/or other materials provided with the
+distribution.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
+BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
+OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
+TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
+USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
+DAMAGE.
+
+

If you use this software and you are happy with it, consider sending me a +note, just to gratify my ego. On the other hand, if you use this software and +you are unhappy with it, send me a patch!

+
+
+ + diff --git a/documentation.py b/documentation.py index cdd4fae..aff5d17 100644 --- a/documentation.py +++ b/documentation.py @@ -384,18 +384,20 @@ be locked. Here is a minimalistic example: Each call to ``write`` will create a new writer thread, but there will be no synchronization problems since ``write`` is locked. ->>> write("data1") # doctest: +ELLIPSIS - - ->>> time.sleep(.1) # wait a bit, so we are sure data2 is written after data1 - ->>> write("data2") # doctest: +ELLIPSIS - - ->>> time.sleep(2) # wait for the writers to complete +.. code-block:: python ->>> print datalist -['data1', 'data2'] + >>> write("data1") # doctest: +ELLIPSIS + + + >>> time.sleep(.1) # wait a bit, so we are sure data2 is written after data1 + + >>> write("data2") # doctest: +ELLIPSIS + + + >>> time.sleep(2) # wait for the writers to complete + + >>> print datalist + ['data1', 'data2'] The ``FunctionMaker`` class --------------------------------------------------------------- @@ -729,23 +731,32 @@ a *copy* of the original function dictionary Compatibility notes --------------------------------------------------------------- -Version 3.0 is a complete rewrite of the original implementation. -It is mostly compatible with the past, a part for a few differences. - -First of all, the utilites ``get_info`` and ``new_wrapper``, available -in the 2.X versions, have been deprecated and they will be removed -in the future. For the moment, using them raises a ``DeprecationWarning``. -Incidentally, the functionality has been implemented through a -decorator which makes a good example for this documentation: - -$$deprecated - -``get_info`` has been removed since it was little used and since it had -to be changed anyway to work with Python 3.0; ``new_wrapper`` has been -removed since it was useless: its major use case (converting -signature changing decorators to signature preserving decorators) -has been subsumed by ``decorator_apply`` -and the other use case can be managed with the ``FunctionMaker``. +Version 3.2 is the first version of the ``decorator`` module to officially +support Python 3.0. Actually, the module has supported Python 3.0 from +the beginning, via the ``2to3`` conversion tool, but this step has +been now integrated in the build process, thanks to the distribute_ +project, the Python 3-compatible replacement of easy_install. +The hard work (for me) has been converting the documentation and the +doctests. This has been possibly only now that docutils_ and pygments_ +have been ported to Python 3. + +The ``decorator`` module *per se* does not contain any change, apart +from the removal of the functions ``get_info`` and ``new_wrapper``, +which have been deprecated for years. ``get_info`` has been removed +since it was little used and since it had to be changed anyway to work +with Python 3.0; ``new_wrapper`` has been removed since it was +useless: its major use case (converting signature changing decorators +to signature preserving decorators) has been subsumed by +``decorator_apply`` and the other use case can be managed with the +``FunctionMaker``. + +There are a few changes in the documentation: I removed the +``decorator_factory`` example, which was confusing some of my users, +and I removed the part about exotic signatures in the Python 3 +documentation, since Python 3 does not support them. +Notice that there is no support for Python 3 `function annotations`_ +since it seems premature at the moment, when most people are +still using Python 2.X. Finally ``decorator`` cannot be used as a class decorator and the `functionality introduced in version 2.3`_ has been removed. That @@ -755,25 +766,21 @@ All these changes should not cause any trouble, since they were all rarely used features. Should you have any trouble, you can always downgrade to the 2.3 version. -The examples shown here have been tested with Python 2.5. Python 2.4 +The examples shown here have been tested with Python 2.6. Python 2.4 is also supported - of course the examples requiring the ``with`` -statement will not work there. Python 2.6 works fine, but if you +statement will not work there. Python 2.5 works fine, but if you run the examples here in the interactive interpreter you will notice a few differences since ``getargspec`` returns an ``ArgSpec`` namedtuple instead of a regular tuple. That means that running the file ``documentation.py`` under Python 2.5 will a few errors, but -they are not serious. Python 3.0 is kind of supported too. -Simply run the script ``2to3`` on the module -``decorator.py`` and you will get a version of the code running -with Python 3.0 (at least, I did some simple checks and it seemed -to work). However there is no support for `function annotations`_ yet -since it seems premature at this moment (most people are -still using Python 2.5). +they are not serious. .. _functionality introduced in version 2.3: http://www.phyast.pitt.edu/~micheles/python/documentation.html#class-decorators-and-decorator-factories .. _function annotations: http://www.python.org/dev/peps/pep-3107/ - +.. _distribute: http://packages.python.org/distribute/ +.. _docutils: http://docutils.sourceforge.net/ +.. _pygments: http://pygments.org/ LICENCE --------------------------------------------- diff --git a/documentation3.html b/documentation3.html new file mode 100644 index 0000000..209dd61 --- /dev/null +++ b/documentation3.html @@ -0,0 +1,966 @@ + + + + + + +The decorator module + + + + +
+

The decorator module

+ +++ + + + + + + + + + + + + + + + +
Author:Michele Simionato
E-mail:michele.simionato@gmail.com
Version:3.2.0 (2010-05-22)
Requires:Python 2.4+
Download page:http://pypi.python.org/pypi/decorator/3.2.0
Installation:easy_install decorator
License:BSD license
+ +
+

Introduction

+

Python decorators are an interesting example of why syntactic sugar +matters. In principle, their introduction in Python 2.4 changed +nothing, since they do not provide any new functionality which was not +already present in the language. In practice, their introduction has +significantly changed the way we structure our programs in Python. I +believe the change is for the best, and that decorators are a great +idea since:

+
    +
  • decorators help reducing boilerplate code;
  • +
  • decorators help separation of concerns;
  • +
  • decorators enhance readability and maintenability;
  • +
  • decorators are explicit.
  • +
+

Still, as of now, writing custom decorators correctly requires +some experience and it is not as easy as it could be. For instance, +typical implementations of decorators involve nested functions, and +we all know that flat is better than nested.

+

The aim of the decorator module it to simplify the usage of +decorators for the average programmer, and to popularize decorators by +showing various non-trivial examples. Of course, as all techniques, +decorators can be abused (I have seen that) and you should not try to +solve every problem with a decorator, just because you can.

+

You may find the source code for all the examples +discussed here in the documentation.py file, which contains +this documentation in the form of doctests.

+
+
+

Definitions

+

Technically speaking, any Python object which can be called with one argument +can be used as a decorator. However, this definition is somewhat too large +to be really useful. It is more convenient to split the generic class of +decorators in two subclasses:

+
    +
  • signature-preserving decorators, i.e. callable objects taking a +function as input and returning a function with the same +signature as output;
  • +
  • signature-changing decorators, i.e. decorators that change +the signature of their input function, or decorators returning +non-callable objects.
  • +
+

Signature-changing decorators have their use: for instance the +builtin classes staticmethod and classmethod are in this +group, since they take functions and return descriptor objects which +are not functions, nor callables.

+

However, signature-preserving decorators are more common and easier to +reason about; in particular signature-preserving decorators can be +composed together whereas other decorators in general cannot.

+

Writing signature-preserving decorators from scratch is not that +obvious, especially if one wants to define proper decorators that +can accept functions with any signature. A simple example will clarify +the issue.

+
+
+

Statement of the problem

+

A very common use case for decorators is the memoization of functions. +A memoize decorator works by caching +the result of the function call in a dictionary, so that the next time +the function is called with the same input parameters the result is retrieved +from the cache and not recomputed. There are many implementations of +memoize in http://www.python.org/moin/PythonDecoratorLibrary, +but they do not preserve the signature. +A simple implementation for Python 2.5 could be the following (notice +that in general it is impossible to memoize correctly something +that depends on non-hashable arguments):

+
+def memoize25(func):
+    func.cache = {}
+    def memoize(*args, **kw):
+        if kw: # frozenset is used to ensure hashability
+            key = args, frozenset(kw.iteritems())
+        else:
+            key = args
+        cache = func.cache
+        if key in cache:
+            return cache[key]
+        else:
+            cache[key] = result = func(*args, **kw)
+            return result
+    return functools.update_wrapper(memoize, func)
+
+

Here we used the functools.update_wrapper utility, which has +been added in Python 2.5 expressly to simplify the definition of decorators +(in older versions of Python you need to copy the function attributes +__name__, __doc__, __module__ and __dict__ +from the original function to the decorated function by hand).

+

The implementation above works in the sense that the decorator +can accept functions with generic signatures; unfortunately this +implementation does not define a signature-preserving decorator, since in +general memoize25 returns a function with a +different signature from the original function.

+

Consider for instance the following case:

+
+
>>> @memoize25
+... def f1(x):
+...     time.sleep(1) # simulate some long computation
+...     return x
+
+ +
+

Here the original function takes a single argument named x, +but the decorated function takes any number of arguments and +keyword arguments:

+
+
>>> from inspect import getargspec
+>>> print(getargspec(f1))
+ArgSpec(args=[], varargs='args', keywords='kw', defaults=None)
+
+ +
+

This means that introspection tools such as pydoc will give +wrong informations about the signature of f1. This is pretty bad: +pydoc will tell you that the function accepts a generic signature +*args, **kw, but when you try to call the function with more than an +argument, you will get an error:

+
+
>>> f1(0, 1)
+Traceback (most recent call last):
+   ...
+TypeError: f1() takes exactly 1 positional argument (2 given)
+
+ +
+
+
+

The solution

+

The solution is to provide a generic factory of generators, which +hides the complexity of making signature-preserving decorators +from the application programmer. The decorator function in +the decorator module is such a factory:

+
+
>>> from decorator import decorator
+
+ +
+

decorator takes two arguments, a caller function describing the +functionality of the decorator and a function to be decorated; it +returns the decorated function. The caller function must have +signature (f, *args, **kw) and it must call the original function f +with arguments args and kw, implementing the wanted capability, +i.e. memoization in this case:

+
+def _memoize(func, *args, **kw):
+    if kw: # frozenset is used to ensure hashability
+        key = args, frozenset(kw.iteritems())
+    else:
+        key = args
+    cache = func.cache # attributed added by memoize
+    if key in cache:
+        return cache[key]
+    else:
+        cache[key] = result = func(*args, **kw)
+        return result
+
+

At this point you can define your decorator as follows:

+
+def memoize(f):
+    f.cache = {}
+    return decorator(_memoize, f)
+
+

The difference with respect to the Python 2.5 approach, which is based +on nested functions, is that the decorator module forces you to lift +the inner function at the outer level (flat is better than nested). +Moreover, you are forced to pass explicitly the function you want to +decorate to the caller function.

+

Here is a test of usage:

+
+
>>> @memoize
+... def heavy_computation():
+...     time.sleep(2)
+...     return "done"
+
+>>> print(heavy_computation()) # the first time it will take 2 seconds
+done
+
+>>> print(heavy_computation()) # the second time it will be instantaneous
+done
+
+ +
+

The signature of heavy_computation is the one you would expect:

+
+
>>> print(getargspec(heavy_computation))
+ArgSpec(args=[], varargs=None, keywords=None, defaults=None)
+
+ +
+
+
+

A trace decorator

+

As an additional example, here is how you can define a trivial +trace decorator, which prints a message everytime the traced +function is called:

+
+def _trace(f, *args, **kw):
+    print("calling %s with args %s, %s" % (f.__name__, args, kw))
+    return f(*args, **kw)
+
+
+def trace(f):
+    return decorator(_trace, f)
+
+

Here is an example of usage:

+
+
>>> @trace
+... def f1(x):
+...     pass
+
+ +
+

It is immediate to verify that f1 works

+
+
>>> f1(0)
+calling f1 with args (0,), {}
+
+ +
+

and it that it has the correct signature:

+
+
>>> print(getargspec(f1))
+ArgSpec(args=['x'], varargs=None, keywords=None, defaults=None)
+
+ +
+

The same decorator works with functions of any signature:

+
+
>>> @trace
+... def f(x, y=1, z=2, *args, **kw):
+...     pass
+
+>>> f(0, 3)
+calling f with args (0, 3, 2), {}
+
+>>> print(getargspec(f))
+ArgSpec(args=['x', 'y', 'z'], varargs='args', keywords='kw', defaults=(1, 2))
+
+ +
+
+
+

decorator is a decorator

+

It may be annoying to write a caller function (like the _trace +function above) and then a trivial wrapper +(def trace(f): return decorator(_trace, f)) every time. For this reason, +the decorator module provides an easy shortcut to convert +the caller function into a signature-preserving decorator: +you can just call decorator with a single argument. +In our example you can just write trace = decorator(_trace). +The decorator function can also be used as a signature-changing +decorator, just as classmethod and staticmethod. +However, classmethod and staticmethod return generic +objects which are not callable, while decorator returns +signature-preserving decorators, i.e. functions of a single argument. +For instance, you can write directly

+
+
>>> @decorator
+... def trace(f, *args, **kw):
+...     print("calling %s with args %s, %s" % (f.__name__, args, kw))
+...     return f(*args, **kw)
+
+ +
+

and now trace will be a decorator. Actually trace is a partial +object which can be used as a decorator:

+
+
>>> trace
+<function trace at 0x...>
+
+ +
+

Here is an example of usage:

+
+
>>> @trace
+... def func(): pass
+
+>>> func()
+calling func with args (), {}
+
+ +
+

If you are using an old Python version (Python 2.4) the +decorator module provides a poor man replacement for +functools.partial.

+
+
+

blocking

+

Sometimes one has to deal with blocking resources, such as stdin, and +sometimes it is best to have back a "busy" message than to block everything. +This behavior can be implemented with a suitable family of decorators, +where the parameter is the busy message:

+
+def blocking(not_avail):
+    def blocking(f, *args, **kw):
+        if not hasattr(f, "thread"): # no thread running
+            def set_result(): f.result = f(*args, **kw)
+            f.thread = threading.Thread(None, set_result)
+            f.thread.start()
+            return not_avail
+        elif f.thread.isAlive():
+            return not_avail
+        else: # the thread is ended, return the stored result
+            del f.thread
+            return f.result
+    return decorator(blocking)
+
+

Functions decorated with blocking will return a busy message if +the resource is unavailable, and the intended result if the resource is +available. For instance:

+
+
>>> @blocking("Please wait ...")
+... def read_data():
+...     time.sleep(3) # simulate a blocking resource
+...     return "some data"
+
+>>> print(read_data()) # data is not available yet
+Please wait ...
+
+>>> time.sleep(1)
+>>> print(read_data()) # data is not available yet
+Please wait ...
+
+>>> time.sleep(1)
+>>> print(read_data()) # data is not available yet
+Please wait ...
+
+>>> time.sleep(1.1) # after 3.1 seconds, data is available
+>>> print(read_data())
+some data
+
+ +
+
+
+

async

+

We have just seen an examples of a simple decorator factory, +implemented as a function returning a decorator. +For more complex situations, it is more +convenient to implement decorator factories as classes returning +callable objects that can be used as signature-preserving +decorators. The suggested pattern to do that is to introduce +a helper method call(self, func, *args, **kw) and to call +it in the __call__(self, func) method.

+

As an example, here I show a decorator +which is able to convert a blocking function into an asynchronous +function. The function, when called, +is executed in a separate thread. Moreover, it is possible to set +three callbacks on_success, on_failure and on_closing, +to specify how to manage the function call. +The implementation is the following:

+
+def on_success(result): # default implementation
+    "Called on the result of the function"
+    return result
+
+
+def on_failure(exc_info): # default implementation
+    "Called if the function fails"
+    pass
+
+
+def on_closing(): # default implementation
+    "Called at the end, both in case of success and failure"
+    pass
+
+
+class Async(object):
+    """
+    A decorator converting blocking functions into asynchronous
+    functions, by using threads or processes. Examples:
+
+    async_with_threads =  Async(threading.Thread)
+    async_with_processes =  Async(multiprocessing.Process)
+    """
+
+    def __init__(self, threadfactory):
+        self.threadfactory = threadfactory
+
+    def __call__(self, func, on_success=on_success,
+                 on_failure=on_failure, on_closing=on_closing):
+        # every decorated function has its own independent thread counter
+        func.counter = itertools.count(1)
+        func.on_success = on_success
+        func.on_failure = on_failure
+        func.on_closing = on_closing
+        return decorator(self.call, func)
+
+    def call(self, func, *args, **kw):
+        def func_wrapper():
+            try:
+                result = func(*args, **kw)
+            except:
+                func.on_failure(sys.exc_info())
+            else:
+                return func.on_success(result)
+            finally:
+                func.on_closing()
+        name = '%s-%s' % (func.__name__, next(func.counter))
+        thread = self.threadfactory(None, func_wrapper, name)
+        thread.start()
+        return thread
+
+

The decorated function returns +the current execution thread, which can be stored and checked later, for +instance to verify that the thread .isAlive().

+

Here is an example of usage. Suppose one wants to write some data to +an external resource which can be accessed by a single user at once +(for instance a printer). Then the access to the writing function must +be locked. Here is a minimalistic example:

+
+
>>> async = Async(threading.Thread)
+
+>>> datalist = [] # for simplicity the written data are stored into a list.
+
+>>> @async
+... def write(data):
+...     # append data to the datalist by locking
+...     with threading.Lock():
+...         time.sleep(1) # emulate some long running operation
+...         datalist.append(data)
+...     # other operations not requiring a lock here
+
+ +
+

Each call to write will create a new writer thread, but there will +be no synchronization problems since write is locked.

+
+
>>> write("data1")
+<Thread(write-1, started...)>
+
+>>> time.sleep(.1) # wait a bit, so we are sure data2 is written after data1
+
+>>> write("data2")
+<Thread(write-2, started...)>
+
+>>> time.sleep(2) # wait for the writers to complete
+
+>>> print(datalist)
+['data1', 'data2']
+
+ +
+
+
+

The FunctionMaker class

+

You may wonder about how the functionality of the decorator module +is implemented. The basic building block is +a FunctionMaker class which is able to generate on the fly +functions with a given name and signature from a function template +passed as a string. Generally speaking, you should not need to +resort to FunctionMaker when writing ordinary decorators, but +it is handy in some circumstances. You will see an example shortly, in +the implementation of a cool decorator utility (decorator_apply).

+

FunctionMaker provides a .create classmethod which +takes as input the name, signature, and body of the function +we want to generate as well as the execution environment +were the function is generated by exec. Here is an example:

+
+
>>> def f(*args, **kw): # a function with a generic signature
+...     print(args, kw)
+
+>>> f1 = FunctionMaker.create('f1(a, b)', 'f(a, b)', dict(f=f))
+>>> f1(1,2)
+(1, 2) {}
+
+ +
+

It is important to notice that the function body is interpolated +before being executed, so be careful with the % sign!

+

FunctionMaker.create also accepts keyword arguments and such +arguments are attached to the resulting function. This is useful +if you want to set some function attributes, for instance the +docstring __doc__.

+

For debugging/introspection purposes it may be useful to see +the source code of the generated function; to do that, just +pass the flag addsource=True and a __source__ attribute will +be added to the generated function:

+
+
>>> f1 = FunctionMaker.create(
+...     'f1(a, b)', 'f(a, b)', dict(f=f), addsource=True)
+>>> print(f1.__source__)
+def f1(a, b):
+    f(a, b)
+<BLANKLINE>
+
+ +
+

FunctionMaker.create can take as first argument a string, +as in the examples before, or a function. This is the most common +usage, since typically you want to decorate a pre-existing +function. A framework author may want to use directly FunctionMaker.create +instead of decorator, since it gives you direct access to the body +of the generated function. For instance, suppose you want to instrument +the __init__ methods of a set of classes, by preserving their +signature (such use case is not made up; this is done in SQAlchemy +and in other frameworks). When the first argument of FunctionMaker.create +is a function, a FunctionMaker object is instantiated internally, +with attributes args, varargs, +keywords and defaults which are the +the return values of the standard library function inspect.getargspec. +For each argument in the args (which is a list of strings containing +the names of the mandatory arguments) an attribute arg0, arg1, +..., argN is also generated. Finally, there is a signature +attribute, a string with the signature of the original function.

+

Notice that while I do not have plans +to change or remove the functionality provided in the +FunctionMaker class, I do not guarantee that it will stay +unchanged forever. For instance, right now I am using the traditional +string interpolation syntax for function templates, but Python 2.6 +and Python 3.0 provide a newer interpolation syntax and I may use +the new syntax in the future. +On the other hand, the functionality provided by +decorator has been there from version 0.1 and it is guaranteed to +stay there forever.

+
+
+

Getting the source code

+

Internally FunctionMaker.create uses exec to generate the +decorated function. Therefore +inspect.getsource will not work for decorated functions. That +means that the usual '??' trick in IPython will give you the (right on +the spot) message Dynamically generated function. No source code +available. In the past I have considered this acceptable, since +inspect.getsource does not really work even with regular +decorators. In that case inspect.getsource gives you the wrapper +source code which is probably not what you want:

+
+def identity_dec(func):
+    def wrapper(*args, **kw):
+        return func(*args, **kw)
+    return wrapper
+
+
+
@identity_dec
+def example(): pass
+
+>>> print(inspect.getsource(example))
+    def wrapper(*args, **kw):
+        return func(*args, **kw)
+<BLANKLINE>
+
+ +
+

(see bug report 1764286 for an explanation of what is happening). +Unfortunately the bug is still there, even in Python 2.6 and 3.0. +There is however a workaround. The decorator module adds an +attribute .undecorated to the decorated function, containing +a reference to the original function. The easy way to get +the source code is to call inspect.getsource on the +undecorated function:

+
+
>>> print(inspect.getsource(factorial.undecorated))
+@tail_recursive
+def factorial(n, acc=1):
+    "The good old factorial"
+    if n == 0: return acc
+    return factorial(n-1, n*acc)
+<BLANKLINE>
+
+ +
+
+
+

Dealing with third party decorators

+

Sometimes you find on the net some cool decorator that you would +like to include in your code. However, more often than not the cool +decorator is not signature-preserving. Therefore you may want an easy way to +upgrade third party decorators to signature-preserving decorators without +having to rewrite them in terms of decorator. You can use a +FunctionMaker to implement that functionality as follows:

+
+def decorator_apply(dec, func):
+    """
+    Decorate a function by preserving the signature even if dec
+    is not a signature-preserving decorator.
+    """
+    return FunctionMaker.create(
+        func, 'return decorated(%(signature)s)',
+        dict(decorated=dec(func)), undecorated=func)
+
+

decorator_apply sets the attribute .undecorated of the generated +function to the original function, so that you can get the right +source code.

+

Notice that I am not providing this functionality in the decorator +module directly since I think it is best to rewrite the decorator rather +than adding an additional level of indirection. However, practicality +beats purity, so you can add decorator_apply to your toolbox and +use it if you need to.

+

In order to give an example of usage of decorator_apply, I will show a +pretty slick decorator that converts a tail-recursive function in an iterative +function. I have shamelessly stolen the basic idea from Kay Schluehr's recipe +in the Python Cookbook, +http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/496691.

+
+class TailRecursive(object):
+    """
+    tail_recursive decorator based on Kay Schluehr's recipe
+    http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/496691
+    with improvements by me and George Sakkis.
+    """
+
+    def __init__(self, func):
+        self.func = func
+        self.firstcall = True
+        self.CONTINUE = object() # sentinel
+
+    def __call__(self, *args, **kwd):
+        CONTINUE = self.CONTINUE
+        if self.firstcall:
+            func = self.func
+            self.firstcall = False
+            try:
+                while True:
+                    result = func(*args, **kwd)
+                    if result is CONTINUE: # update arguments
+                        args, kwd = self.argskwd
+                    else: # last call
+                        return result
+            finally:
+                self.firstcall = True
+        else: # return the arguments of the tail call
+            self.argskwd = args, kwd
+            return CONTINUE
+
+

Here the decorator is implemented as a class returning callable +objects.

+
+def tail_recursive(func):
+    return decorator_apply(TailRecursive, func)
+
+

Here is how you apply the upgraded decorator to the good old factorial:

+
+@tail_recursive
+def factorial(n, acc=1):
+    "The good old factorial"
+    if n == 0: return acc
+    return factorial(n-1, n*acc)
+
+
+
>>> print(factorial(4))
+24
+
+ +
+

This decorator is pretty impressive, and should give you some food for +your mind ;) Notice that there is no recursion limit now, and you can +easily compute factorial(1001) or larger without filling the stack +frame. Notice also that the decorator will not work on functions which +are not tail recursive, such as the following

+
+def fact(n): # this is not tail-recursive
+    if n == 0: return 1
+    return n * fact(n-1)
+
+

(reminder: a function is tail recursive if it either returns a value without +making a recursive call, or returns directly the result of a recursive +call).

+
+
+

Caveats and limitations

+

The first thing you should be aware of, it the fact that decorators +have a performance penalty. +The worse case is shown by the following example:

+
+$ cat performance.sh
+python3 -m timeit -s "
+from decorator import decorator
+
+@decorator
+def do_nothing(func, *args, **kw):
+    return func(*args, **kw)
+
+@do_nothing
+def f():
+    pass
+" "f()"
+
+python3 -m timeit -s "
+def f():
+    pass
+" "f()"
+
+

On my MacBook, using the do_nothing decorator instead of the +plain function is more than three times slower:

+
+$ bash performance.sh
+1000000 loops, best of 3: 0.669 usec per loop
+1000000 loops, best of 3: 0.181 usec per loop
+
+

It should be noted that a real life function would probably do +something more useful than f here, and therefore in real life the +performance penalty could be completely negligible. As always, the +only way to know if there is +a penalty in your specific use case is to measure it.

+

You should be aware that decorators will make your tracebacks +longer and more difficult to understand. Consider this example:

+
+
>>> @trace
+... def f():
+...     1/0
+
+ +
+

Calling f() will give you a ZeroDivisionError, but since the +function is decorated the traceback will be longer:

+
+
>>> f()
+Traceback (most recent call last):
+  ...
+     File "<string>", line 2, in f
+     File "<doctest __main__[22]>", line 4, in trace
+       return f(*args, **kw)
+     File "<doctest __main__[51]>", line 3, in f
+       1/0
+ZeroDivisionError: int division or modulo by zero
+
+ +
+

You see here the inner call to the decorator trace, which calls +f(*args, **kw), and a reference to File "<string>", line 2, in f. +This latter reference is due to the fact that internally the decorator +module uses exec to generate the decorated function. Notice that +exec is not responsibile for the performance penalty, since is the +called only once at function decoration time, and not every time +the decorated function is called.

+

At present, there is no clean way to avoid exec. A clean solution +would require to change the CPython implementation of functions and +add an hook to make it possible to change their signature directly. +That could happen in future versions of Python (see PEP 362) and +then the decorator module would become obsolete. However, at present, +even in Python 3.1 it is impossible to change the function signature +directly, therefore the decorator module is still useful. +Actually, this is one of the main reasons why I keep maintaining +the module and releasing new versions.

+

In the present implementation, decorators generated by decorator +can only be used on user-defined Python functions or methods, not on generic +callable objects, nor on built-in functions, due to limitations of the +inspect module in the standard library.

+

There is a restriction on the names of the arguments: for instance, +if try to call an argument _call_ or _func_ +you will get a NameError:

+
+
>>> @trace
+... def f(_func_): print(f)
+...
+Traceback (most recent call last):
+  ...
+NameError: _func_ is overridden in
+def f(_func_):
+    return _call_(_func_, _func_)
+
+ +
+

Finally, the implementation is such that the decorated function contains +a copy of the original function dictionary +(vars(decorated_f) is not vars(f)):

+
+
>>> def f(): pass # the original function
+>>> f.attr1 = "something" # setting an attribute
+>>> f.attr2 = "something else" # setting another attribute
+
+>>> traced_f = trace(f) # the decorated function
+
+>>> traced_f.attr1
+'something'
+>>> traced_f.attr2 = "something different" # setting attr
+>>> f.attr2 # the original attribute did not change
+'something else'
+
+ +
+
+
+

Compatibility notes

+

Version 3.2 is the first version of the decorator module to officially +support Python 3.0. Actually, the module has supported Python 3.0 from +the beginning, via the 2to3 conversion tool, but this step has +been now integrated in the build process, thanks to the distribute +project, the Python 3-compatible replacement of easy_install. +The hard work (for me) has been converting the documentation and the +doctests. This has been possibly only now that docutils and pygments +have been ported to Python 3.

+

The decorator module per se does not contain any change, apart +from the removal of the functions get_info and new_wrapper, +which have been deprecated for years. get_info has been removed +since it was little used and since it had to be changed anyway to work +with Python 3.0; new_wrapper has been removed since it was +useless: its major use case (converting signature changing decorators +to signature preserving decorators) has been subsumed by +decorator_apply and the other use case can be managed with the +FunctionMaker.

+

There are a few changes in the documentation: I removed the +decorator_factory example, which was confusing some of my users, +and I removed the part about exotic signatures in the Python 3 +documentation, since Python 3 does not support them. +Notice that there is no support for Python 3 function annotations +since it seems premature at the moment, when most people are +still using Python 2.X.

+

Finally decorator cannot be used as a class decorator and the +functionality introduced in version 2.3 has been removed. That +means that in order to define decorator factories with classes you +need to define the __call__ method explicitly (no magic anymore). +All these changes should not cause any trouble, since they were +all rarely used features. Should you have any trouble, you can always +downgrade to the 2.3 version.

+

The examples shown here have been tested with Python 2.6. Python 2.4 +is also supported - of course the examples requiring the with +statement will not work there. Python 2.5 works fine, but if you +run the examples here in the interactive interpreter +you will notice a few differences since +getargspec returns an ArgSpec namedtuple instead of a regular +tuple. That means that running the file +documentation.py under Python 2.5 will a few errors, but +they are not serious.

+
+
+

LICENCE

+

Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met:

+
+Copyright (c) 2005, Michele Simionato
+All rights reserved.
+
+Redistributions of source code must retain the above copyright
+notice, this list of conditions and the following disclaimer.
+Redistributions in bytecode form must reproduce the above copyright
+notice, this list of conditions and the following disclaimer in
+the documentation and/or other materials provided with the
+distribution.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
+BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
+OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
+TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
+USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
+DAMAGE.
+
+

If you use this software and you are happy with it, consider sending me a +note, just to gratify my ego. On the other hand, if you use this software and +you are unhappy with it, send me a patch!

+
+
+ + diff --git a/documentation3.py b/documentation3.py new file mode 100644 index 0000000..259d0ba --- /dev/null +++ b/documentation3.py @@ -0,0 +1,1006 @@ +r""" +The ``decorator`` module +============================================================= + +:Author: Michele Simionato +:E-mail: michele.simionato@gmail.com +:Version: $VERSION ($DATE) +:Requires: Python 2.4+ +:Download page: http://pypi.python.org/pypi/decorator/$VERSION +:Installation: ``easy_install decorator`` +:License: BSD license + +.. contents:: + +Introduction +------------------------------------------------ + +Python decorators are an interesting example of why syntactic sugar +matters. In principle, their introduction in Python 2.4 changed +nothing, since they do not provide any new functionality which was not +already present in the language. In practice, their introduction has +significantly changed the way we structure our programs in Python. I +believe the change is for the best, and that decorators are a great +idea since: + +* decorators help reducing boilerplate code; +* decorators help separation of concerns; +* decorators enhance readability and maintenability; +* decorators are explicit. + +Still, as of now, writing custom decorators correctly requires +some experience and it is not as easy as it could be. For instance, +typical implementations of decorators involve nested functions, and +we all know that flat is better than nested. + +The aim of the ``decorator`` module it to simplify the usage of +decorators for the average programmer, and to popularize decorators by +showing various non-trivial examples. Of course, as all techniques, +decorators can be abused (I have seen that) and you should not try to +solve every problem with a decorator, just because you can. + +You may find the source code for all the examples +discussed here in the ``documentation.py`` file, which contains +this documentation in the form of doctests. + +Definitions +------------------------------------ + +Technically speaking, any Python object which can be called with one argument +can be used as a decorator. However, this definition is somewhat too large +to be really useful. It is more convenient to split the generic class of +decorators in two subclasses: + ++ *signature-preserving* decorators, i.e. callable objects taking a + function as input and returning a function *with the same + signature* as output; + ++ *signature-changing* decorators, i.e. decorators that change + the signature of their input function, or decorators returning + non-callable objects. + +Signature-changing decorators have their use: for instance the +builtin classes ``staticmethod`` and ``classmethod`` are in this +group, since they take functions and return descriptor objects which +are not functions, nor callables. + +However, signature-preserving decorators are more common and easier to +reason about; in particular signature-preserving decorators can be +composed together whereas other decorators in general cannot. + +Writing signature-preserving decorators from scratch is not that +obvious, especially if one wants to define proper decorators that +can accept functions with any signature. A simple example will clarify +the issue. + +Statement of the problem +------------------------------ + +A very common use case for decorators is the memoization of functions. +A ``memoize`` decorator works by caching +the result of the function call in a dictionary, so that the next time +the function is called with the same input parameters the result is retrieved +from the cache and not recomputed. There are many implementations of +``memoize`` in http://www.python.org/moin/PythonDecoratorLibrary, +but they do not preserve the signature. +A simple implementation for Python 2.5 could be the following (notice +that in general it is impossible to memoize correctly something +that depends on non-hashable arguments): + +$$memoize25 + +Here we used the functools.update_wrapper_ utility, which has +been added in Python 2.5 expressly to simplify the definition of decorators +(in older versions of Python you need to copy the function attributes +``__name__``, ``__doc__``, ``__module__`` and ``__dict__`` +from the original function to the decorated function by hand). + +.. _functools.update_wrapper: http://www.python.org/doc/2.5.2/lib/module-functools.html + +The implementation above works in the sense that the decorator +can accept functions with generic signatures; unfortunately this +implementation does *not* define a signature-preserving decorator, since in +general ``memoize25`` returns a function with a +*different signature* from the original function. + +Consider for instance the following case: + +.. code-block:: python + + >>> @memoize25 + ... def f1(x): + ... time.sleep(1) # simulate some long computation + ... return x + +Here the original function takes a single argument named ``x``, +but the decorated function takes any number of arguments and +keyword arguments: + +.. code-block:: python + + >>> from inspect import getargspec + >>> print(getargspec(f1)) + ArgSpec(args=[], varargs='args', keywords='kw', defaults=None) + +This means that introspection tools such as pydoc will give +wrong informations about the signature of ``f1``. This is pretty bad: +pydoc will tell you that the function accepts a generic signature +``*args``, ``**kw``, but when you try to call the function with more than an +argument, you will get an error: + +.. code-block:: python + + >>> f1(0, 1) + Traceback (most recent call last): + ... + TypeError: f1() takes exactly 1 positional argument (2 given) + +The solution +----------------------------------------- + +The solution is to provide a generic factory of generators, which +hides the complexity of making signature-preserving decorators +from the application programmer. The ``decorator`` function in +the ``decorator`` module is such a factory: + +.. code-block:: python + + >>> from decorator import decorator + +``decorator`` takes two arguments, a caller function describing the +functionality of the decorator and a function to be decorated; it +returns the decorated function. The caller function must have +signature ``(f, *args, **kw)`` and it must call the original function ``f`` +with arguments ``args`` and ``kw``, implementing the wanted capability, +i.e. memoization in this case: + +$$_memoize + +At this point you can define your decorator as follows: + +$$memoize + +The difference with respect to the Python 2.5 approach, which is based +on nested functions, is that the decorator module forces you to lift +the inner function at the outer level (*flat is better than nested*). +Moreover, you are forced to pass explicitly the function you want to +decorate to the caller function. + +Here is a test of usage: + +.. code-block:: python + + >>> @memoize + ... def heavy_computation(): + ... time.sleep(2) + ... return "done" + + >>> print(heavy_computation()) # the first time it will take 2 seconds + done + + >>> print(heavy_computation()) # the second time it will be instantaneous + done + +The signature of ``heavy_computation`` is the one you would expect: + +.. code-block:: python + + >>> print(getargspec(heavy_computation)) + ArgSpec(args=[], varargs=None, keywords=None, defaults=None) + +A ``trace`` decorator +------------------------------------------------------ + +As an additional example, here is how you can define a trivial +``trace`` decorator, which prints a message everytime the traced +function is called: + +$$_trace + +$$trace + +Here is an example of usage: + +.. code-block:: python + + >>> @trace + ... def f1(x): + ... pass + +It is immediate to verify that ``f1`` works + +.. code-block:: python + + >>> f1(0) + calling f1 with args (0,), {} + +and it that it has the correct signature: + +.. code-block:: python + + >>> print(getargspec(f1)) + ArgSpec(args=['x'], varargs=None, keywords=None, defaults=None) + +The same decorator works with functions of any signature: + +.. code-block:: python + + >>> @trace + ... def f(x, y=1, z=2, *args, **kw): + ... pass + + >>> f(0, 3) + calling f with args (0, 3, 2), {} + + >>> print(getargspec(f)) + ArgSpec(args=['x', 'y', 'z'], varargs='args', keywords='kw', defaults=(1, 2)) + +``decorator`` is a decorator +--------------------------------------------- + +It may be annoying to write a caller function (like the ``_trace`` +function above) and then a trivial wrapper +(``def trace(f): return decorator(_trace, f)``) every time. For this reason, +the ``decorator`` module provides an easy shortcut to convert +the caller function into a signature-preserving decorator: +you can just call ``decorator`` with a single argument. +In our example you can just write ``trace = decorator(_trace)``. +The ``decorator`` function can also be used as a signature-changing +decorator, just as ``classmethod`` and ``staticmethod``. +However, ``classmethod`` and ``staticmethod`` return generic +objects which are not callable, while ``decorator`` returns +signature-preserving decorators, i.e. functions of a single argument. +For instance, you can write directly + +.. code-block:: python + + >>> @decorator + ... def trace(f, *args, **kw): + ... print("calling %s with args %s, %s" % (f.__name__, args, kw)) + ... return f(*args, **kw) + +and now ``trace`` will be a decorator. Actually ``trace`` is a ``partial`` +object which can be used as a decorator: + +.. code-block:: python + + >>> trace # doctest: +ELLIPSIS + + +Here is an example of usage: + +.. code-block:: python + + >>> @trace + ... def func(): pass + + >>> func() + calling func with args (), {} + +If you are using an old Python version (Python 2.4) the +``decorator`` module provides a poor man replacement for +``functools.partial``. + +``blocking`` +------------------------------------------- + +Sometimes one has to deal with blocking resources, such as ``stdin``, and +sometimes it is best to have back a "busy" message than to block everything. +This behavior can be implemented with a suitable family of decorators, +where the parameter is the busy message: + +$$blocking + +Functions decorated with ``blocking`` will return a busy message if +the resource is unavailable, and the intended result if the resource is +available. For instance: + +.. code-block:: python + + >>> @blocking("Please wait ...") + ... def read_data(): + ... time.sleep(3) # simulate a blocking resource + ... return "some data" + + >>> print(read_data()) # data is not available yet + Please wait ... + + >>> time.sleep(1) + >>> print(read_data()) # data is not available yet + Please wait ... + + >>> time.sleep(1) + >>> print(read_data()) # data is not available yet + Please wait ... + + >>> time.sleep(1.1) # after 3.1 seconds, data is available + >>> print(read_data()) + some data + +``async`` +-------------------------------------------- + +We have just seen an examples of a simple decorator factory, +implemented as a function returning a decorator. +For more complex situations, it is more +convenient to implement decorator factories as classes returning +callable objects that can be used as signature-preserving +decorators. The suggested pattern to do that is to introduce +a helper method ``call(self, func, *args, **kw)`` and to call +it in the ``__call__(self, func)`` method. + +As an example, here I show a decorator +which is able to convert a blocking function into an asynchronous +function. The function, when called, +is executed in a separate thread. Moreover, it is possible to set +three callbacks ``on_success``, ``on_failure`` and ``on_closing``, +to specify how to manage the function call. +The implementation is the following: + +$$on_success +$$on_failure +$$on_closing +$$Async + +The decorated function returns +the current execution thread, which can be stored and checked later, for +instance to verify that the thread ``.isAlive()``. + +Here is an example of usage. Suppose one wants to write some data to +an external resource which can be accessed by a single user at once +(for instance a printer). Then the access to the writing function must +be locked. Here is a minimalistic example: + +.. code-block:: python + + >>> async = Async(threading.Thread) + + >>> datalist = [] # for simplicity the written data are stored into a list. + + >>> @async + ... def write(data): + ... # append data to the datalist by locking + ... with threading.Lock(): + ... time.sleep(1) # emulate some long running operation + ... datalist.append(data) + ... # other operations not requiring a lock here + +Each call to ``write`` will create a new writer thread, but there will +be no synchronization problems since ``write`` is locked. + +.. code-block:: python + + >>> write("data1") # doctest: +ELLIPSIS + + + >>> time.sleep(.1) # wait a bit, so we are sure data2 is written after data1 + + >>> write("data2") # doctest: +ELLIPSIS + + + >>> time.sleep(2) # wait for the writers to complete + + >>> print(datalist) + ['data1', 'data2'] + +The ``FunctionMaker`` class +--------------------------------------------------------------- + +You may wonder about how the functionality of the ``decorator`` module +is implemented. The basic building block is +a ``FunctionMaker`` class which is able to generate on the fly +functions with a given name and signature from a function template +passed as a string. Generally speaking, you should not need to +resort to ``FunctionMaker`` when writing ordinary decorators, but +it is handy in some circumstances. You will see an example shortly, in +the implementation of a cool decorator utility (``decorator_apply``). + +``FunctionMaker`` provides a ``.create`` classmethod which +takes as input the name, signature, and body of the function +we want to generate as well as the execution environment +were the function is generated by ``exec``. Here is an example: + +.. code-block:: python + + >>> def f(*args, **kw): # a function with a generic signature + ... print(args, kw) + + >>> f1 = FunctionMaker.create('f1(a, b)', 'f(a, b)', dict(f=f)) + >>> f1(1,2) + (1, 2) {} + +It is important to notice that the function body is interpolated +before being executed, so be careful with the ``%`` sign! + +``FunctionMaker.create`` also accepts keyword arguments and such +arguments are attached to the resulting function. This is useful +if you want to set some function attributes, for instance the +docstring ``__doc__``. + +For debugging/introspection purposes it may be useful to see +the source code of the generated function; to do that, just +pass the flag ``addsource=True`` and a ``__source__`` attribute will +be added to the generated function: + +.. code-block:: python + + >>> f1 = FunctionMaker.create( + ... 'f1(a, b)', 'f(a, b)', dict(f=f), addsource=True) + >>> print(f1.__source__) + def f1(a, b): + f(a, b) + + +``FunctionMaker.create`` can take as first argument a string, +as in the examples before, or a function. This is the most common +usage, since typically you want to decorate a pre-existing +function. A framework author may want to use directly ``FunctionMaker.create`` +instead of ``decorator``, since it gives you direct access to the body +of the generated function. For instance, suppose you want to instrument +the ``__init__`` methods of a set of classes, by preserving their +signature (such use case is not made up; this is done in SQAlchemy +and in other frameworks). When the first argument of ``FunctionMaker.create`` +is a function, a ``FunctionMaker`` object is instantiated internally, +with attributes ``args``, ``varargs``, +``keywords`` and ``defaults`` which are the +the return values of the standard library function ``inspect.getargspec``. +For each argument in the ``args`` (which is a list of strings containing +the names of the mandatory arguments) an attribute ``arg0``, ``arg1``, +..., ``argN`` is also generated. Finally, there is a ``signature`` +attribute, a string with the signature of the original function. + +Notice that while I do not have plans +to change or remove the functionality provided in the +``FunctionMaker`` class, I do not guarantee that it will stay +unchanged forever. For instance, right now I am using the traditional +string interpolation syntax for function templates, but Python 2.6 +and Python 3.0 provide a newer interpolation syntax and I may use +the new syntax in the future. +On the other hand, the functionality provided by +``decorator`` has been there from version 0.1 and it is guaranteed to +stay there forever. + +Getting the source code +--------------------------------------------------- + +Internally ``FunctionMaker.create`` uses ``exec`` to generate the +decorated function. Therefore +``inspect.getsource`` will not work for decorated functions. That +means that the usual '??' trick in IPython will give you the (right on +the spot) message ``Dynamically generated function. No source code +available``. In the past I have considered this acceptable, since +``inspect.getsource`` does not really work even with regular +decorators. In that case ``inspect.getsource`` gives you the wrapper +source code which is probably not what you want: + +$$identity_dec + +.. code-block:: python + + @identity_dec + def example(): pass + + >>> print(inspect.getsource(example)) + def wrapper(*args, **kw): + return func(*args, **kw) + + +(see bug report 1764286_ for an explanation of what is happening). +Unfortunately the bug is still there, even in Python 2.6 and 3.0. +There is however a workaround. The decorator module adds an +attribute ``.undecorated`` to the decorated function, containing +a reference to the original function. The easy way to get +the source code is to call ``inspect.getsource`` on the +undecorated function: + +.. code-block:: python + + >>> print(inspect.getsource(factorial.undecorated)) + @tail_recursive + def factorial(n, acc=1): + "The good old factorial" + if n == 0: return acc + return factorial(n-1, n*acc) + + +.. _1764286: http://bugs.python.org/issue1764286 + +Dealing with third party decorators +----------------------------------------------------------------- + +Sometimes you find on the net some cool decorator that you would +like to include in your code. However, more often than not the cool +decorator is not signature-preserving. Therefore you may want an easy way to +upgrade third party decorators to signature-preserving decorators without +having to rewrite them in terms of ``decorator``. You can use a +``FunctionMaker`` to implement that functionality as follows: + +$$decorator_apply + +``decorator_apply`` sets the attribute ``.undecorated`` of the generated +function to the original function, so that you can get the right +source code. + +Notice that I am not providing this functionality in the ``decorator`` +module directly since I think it is best to rewrite the decorator rather +than adding an additional level of indirection. However, practicality +beats purity, so you can add ``decorator_apply`` to your toolbox and +use it if you need to. + +In order to give an example of usage of ``decorator_apply``, I will show a +pretty slick decorator that converts a tail-recursive function in an iterative +function. I have shamelessly stolen the basic idea from Kay Schluehr's recipe +in the Python Cookbook, +http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/496691. + +$$TailRecursive + +Here the decorator is implemented as a class returning callable +objects. + +$$tail_recursive + +Here is how you apply the upgraded decorator to the good old factorial: + +$$factorial + +.. code-block:: python + + >>> print(factorial(4)) + 24 + +This decorator is pretty impressive, and should give you some food for +your mind ;) Notice that there is no recursion limit now, and you can +easily compute ``factorial(1001)`` or larger without filling the stack +frame. Notice also that the decorator will not work on functions which +are not tail recursive, such as the following + +$$fact + +(reminder: a function is tail recursive if it either returns a value without +making a recursive call, or returns directly the result of a recursive +call). + +Caveats and limitations +------------------------------------------- + +The first thing you should be aware of, it the fact that decorators +have a performance penalty. +The worse case is shown by the following example:: + + $ cat performance.sh + python3 -m timeit -s " + from decorator import decorator + + @decorator + def do_nothing(func, *args, **kw): + return func(*args, **kw) + + @do_nothing + def f(): + pass + " "f()" + + python3 -m timeit -s " + def f(): + pass + " "f()" + +On my MacBook, using the ``do_nothing`` decorator instead of the +plain function is more than three times slower:: + + $ bash performance.sh + 1000000 loops, best of 3: 0.669 usec per loop + 1000000 loops, best of 3: 0.181 usec per loop + +It should be noted that a real life function would probably do +something more useful than ``f`` here, and therefore in real life the +performance penalty could be completely negligible. As always, the +only way to know if there is +a penalty in your specific use case is to measure it. + +You should be aware that decorators will make your tracebacks +longer and more difficult to understand. Consider this example: + +.. code-block:: python + + >>> @trace + ... def f(): + ... 1/0 + +Calling ``f()`` will give you a ``ZeroDivisionError``, but since the +function is decorated the traceback will be longer: + +.. code-block:: python + + >>> f() + Traceback (most recent call last): + ... + File "", line 2, in f + File "", line 4, in trace + return f(*args, **kw) + File "", line 3, in f + 1/0 + ZeroDivisionError: int division or modulo by zero + +You see here the inner call to the decorator ``trace``, which calls +``f(*args, **kw)``, and a reference to ``File "", line 2, in f``. +This latter reference is due to the fact that internally the decorator +module uses ``exec`` to generate the decorated function. Notice that +``exec`` is *not* responsibile for the performance penalty, since is the +called *only once* at function decoration time, and not every time +the decorated function is called. + +At present, there is no clean way to avoid ``exec``. A clean solution +would require to change the CPython implementation of functions and +add an hook to make it possible to change their signature directly. +That could happen in future versions of Python (see PEP 362_) and +then the decorator module would become obsolete. However, at present, +even in Python 3.1 it is impossible to change the function signature +directly, therefore the ``decorator`` module is still useful. +Actually, this is one of the main reasons why I keep maintaining +the module and releasing new versions. + +.. _362: http://www.python.org/dev/peps/pep-0362 + +In the present implementation, decorators generated by ``decorator`` +can only be used on user-defined Python functions or methods, not on generic +callable objects, nor on built-in functions, due to limitations of the +``inspect`` module in the standard library. + +There is a restriction on the names of the arguments: for instance, +if try to call an argument ``_call_`` or ``_func_`` +you will get a ``NameError``: + +.. code-block:: python + + >>> @trace + ... def f(_func_): print(f) + ... + Traceback (most recent call last): + ... + NameError: _func_ is overridden in + def f(_func_): + return _call_(_func_, _func_) + +Finally, the implementation is such that the decorated function contains +a *copy* of the original function dictionary +(``vars(decorated_f) is not vars(f)``): + +.. code-block:: python + + >>> def f(): pass # the original function + >>> f.attr1 = "something" # setting an attribute + >>> f.attr2 = "something else" # setting another attribute + + >>> traced_f = trace(f) # the decorated function + + >>> traced_f.attr1 + 'something' + >>> traced_f.attr2 = "something different" # setting attr + >>> f.attr2 # the original attribute did not change + 'something else' + +Compatibility notes +--------------------------------------------------------------- + +Version 3.2 is the first version of the ``decorator`` module to officially +support Python 3.0. Actually, the module has supported Python 3.0 from +the beginning, via the ``2to3`` conversion tool, but this step has +been now integrated in the build process, thanks to the distribute_ +project, the Python 3-compatible replacement of easy_install. +The hard work (for me) has been converting the documentation and the +doctests. This has been possibly only now that docutils_ and pygments_ +have been ported to Python 3. + +The ``decorator`` module *per se* does not contain any change, apart +from the removal of the functions ``get_info`` and ``new_wrapper``, +which have been deprecated for years. ``get_info`` has been removed +since it was little used and since it had to be changed anyway to work +with Python 3.0; ``new_wrapper`` has been removed since it was +useless: its major use case (converting signature changing decorators +to signature preserving decorators) has been subsumed by +``decorator_apply`` and the other use case can be managed with the +``FunctionMaker``. + +There are a few changes in the documentation: I removed the +``decorator_factory`` example, which was confusing some of my users, +and I removed the part about exotic signatures in the Python 3 +documentation, since Python 3 does not support them. +Notice that there is no support for Python 3 `function annotations`_ +since it seems premature at the moment, when most people are +still using Python 2.X. + +Finally ``decorator`` cannot be used as a class decorator and the +`functionality introduced in version 2.3`_ has been removed. That +means that in order to define decorator factories with classes you +need to define the ``__call__`` method explicitly (no magic anymore). +All these changes should not cause any trouble, since they were +all rarely used features. Should you have any trouble, you can always +downgrade to the 2.3 version. + +The examples shown here have been tested with Python 2.6. Python 2.4 +is also supported - of course the examples requiring the ``with`` +statement will not work there. Python 2.5 works fine, but if you +run the examples here in the interactive interpreter +you will notice a few differences since +``getargspec`` returns an ``ArgSpec`` namedtuple instead of a regular +tuple. That means that running the file +``documentation.py`` under Python 2.5 will a few errors, but +they are not serious. + +.. _functionality introduced in version 2.3: http://www.phyast.pitt.edu/~micheles/python/documentation.html#class-decorators-and-decorator-factories +.. _function annotations: http://www.python.org/dev/peps/pep-3107/ +.. _distribute: http://packages.python.org/distribute/ +.. _docutils: http://docutils.sourceforge.net/ +.. _pygments: http://pygments.org/ + +LICENCE +--------------------------------------------- + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met:: + + Copyright (c) 2005, Michele Simionato + All rights reserved. + + Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + Redistributions in bytecode form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in + the documentation and/or other materials provided with the + distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH + DAMAGE. + +If you use this software and you are happy with it, consider sending me a +note, just to gratify my ego. On the other hand, if you use this software and +you are unhappy with it, send me a patch! +""" +from __future__ import with_statement +import sys, threading, time, functools, inspect, itertools +from decorator import * +from functools import partial +from setup import VERSION + +today = time.strftime('%Y-%m-%d') + +__doc__ = __doc__.replace('$VERSION', VERSION).replace('$DATE', today) + +def decorator_apply(dec, func): + """ + Decorate a function by preserving the signature even if dec + is not a signature-preserving decorator. + """ + return FunctionMaker.create( + func, 'return decorated(%(signature)s)', + dict(decorated=dec(func)), undecorated=func) + +def _trace(f, *args, **kw): + print("calling %s with args %s, %s" % (f.__name__, args, kw)) + return f(*args, **kw) + +def trace(f): + return decorator(_trace, f) + +def on_success(result): # default implementation + "Called on the result of the function" + return result + +def on_failure(exc_info): # default implementation + "Called if the function fails" + pass + +def on_closing(): # default implementation + "Called at the end, both in case of success and failure" + pass + +class Async(object): + """ + A decorator converting blocking functions into asynchronous + functions, by using threads or processes. Examples: + + async_with_threads = Async(threading.Thread) + async_with_processes = Async(multiprocessing.Process) + """ + + def __init__(self, threadfactory): + self.threadfactory = threadfactory + + def __call__(self, func, on_success=on_success, + on_failure=on_failure, on_closing=on_closing): + # every decorated function has its own independent thread counter + func.counter = itertools.count(1) + func.on_success = on_success + func.on_failure = on_failure + func.on_closing = on_closing + return decorator(self.call, func) + + def call(self, func, *args, **kw): + def func_wrapper(): + try: + result = func(*args, **kw) + except: + func.on_failure(sys.exc_info()) + else: + return func.on_success(result) + finally: + func.on_closing() + name = '%s-%s' % (func.__name__, next(func.counter)) + thread = self.threadfactory(None, func_wrapper, name) + thread.start() + return thread + +def identity_dec(func): + def wrapper(*args, **kw): + return func(*args, **kw) + return wrapper + +@identity_dec +def example(): pass + +def memoize25(func): + func.cache = {} + def memoize(*args, **kw): + if kw: # frozenset is used to ensure hashability + key = args, frozenset(kw.iteritems()) + else: + key = args + cache = func.cache + if key in cache: + return cache[key] + else: + cache[key] = result = func(*args, **kw) + return result + return functools.update_wrapper(memoize, func) + +def _memoize(func, *args, **kw): + if kw: # frozenset is used to ensure hashability + key = args, frozenset(kw.iteritems()) + else: + key = args + cache = func.cache # attributed added by memoize + if key in cache: + return cache[key] + else: + cache[key] = result = func(*args, **kw) + return result + +def memoize(f): + f.cache = {} + return decorator(_memoize, f) + +def blocking(not_avail): + def blocking(f, *args, **kw): + if not hasattr(f, "thread"): # no thread running + def set_result(): f.result = f(*args, **kw) + f.thread = threading.Thread(None, set_result) + f.thread.start() + return not_avail + elif f.thread.isAlive(): + return not_avail + else: # the thread is ended, return the stored result + del f.thread + return f.result + return decorator(blocking) + +class User(object): + "Will just be able to see a page" + +class PowerUser(User): + "Will be able to add new pages too" + +class Admin(PowerUser): + "Will be able to delete pages too" + +def get_userclass(): + return User + +class PermissionError(Exception): + pass + +def restricted(user_class): + def restricted(func, *args, **kw): + "Restrict access to a given class of users" + userclass = get_userclass() + if issubclass(userclass, user_class): + return func(*args, **kw) + else: + raise PermissionError( + '%s does not have the permission to run %s!' + % (userclass.__name__, func.__name__)) + return decorator(restricted) + +class Action(object): + """ + >>> a = Action() + >>> a.view() # ok + >>> a.insert() # err + Traceback (most recent call last): + ... + PermissionError: User does not have the permission to run insert! + + """ + @restricted(User) + def view(self): + pass + + @restricted(PowerUser) + def insert(self): + pass + + @restricted(Admin) + def delete(self): + pass + +class TailRecursive(object): + """ + tail_recursive decorator based on Kay Schluehr's recipe + http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/496691 + with improvements by me and George Sakkis. + """ + + def __init__(self, func): + self.func = func + self.firstcall = True + self.CONTINUE = object() # sentinel + + def __call__(self, *args, **kwd): + CONTINUE = self.CONTINUE + if self.firstcall: + func = self.func + self.firstcall = False + try: + while True: + result = func(*args, **kwd) + if result is CONTINUE: # update arguments + args, kwd = self.argskwd + else: # last call + return result + finally: + self.firstcall = True + else: # return the arguments of the tail call + self.argskwd = args, kwd + return CONTINUE + +def tail_recursive(func): + return decorator_apply(TailRecursive, func) + +@tail_recursive +def factorial(n, acc=1): + "The good old factorial" + if n == 0: return acc + return factorial(n-1, n*acc) + +def fact(n): # this is not tail-recursive + if n == 0: return 1 + return n * fact(n-1) + +def a_test_for_pylons(): + """ + In version 3.1.0 decorator(caller) returned a nameless partial + object, thus breaking Pylons. That must not happen again. + + >>> decorator(_memoize).__name__ + '_memoize' + + Here is another bug of version 3.1.1 missing the docstring to avoid: + + >>> factorial.__doc__ + 'The good old factorial' + """ + +if __name__ == '__main__': + import doctest; doctest.testmod() diff --git a/index.html b/index.html new file mode 100644 index 0000000..4f9912a --- /dev/null +++ b/index.html @@ -0,0 +1,330 @@ + + + + + + +Decorator module + + + +
+

Decorator module

+ +

Dependencies:

+

The decorator module requires Python 2.4.

+

Installation:

+

$ python setup.py install

+

Testing:

+

For Python 2.4, 2.5, 2.6, 2.7 run

+

$ python documentation.py

+

for Python 3.X run

+

$ python documentation3.py

+

You will see a few innocuous errors with Python 2.4 and 2.5, because +some inner details such as the introduction of the ArgSpec namedtuple +and Thread.__repr__ changed. You may safely ignore them.

+

Notice:

+

You may get into trouble if in your system there is an older version +of the decorator module; in such a case remove the old version.

+

Documentation:

+

There are two versions of the documentation, one for Python 2 and one +for Python 3 .

+
+ + diff --git a/performance.sh b/performance.sh deleted file mode 100644 index 75e8928..0000000 --- a/performance.sh +++ /dev/null @@ -1,16 +0,0 @@ -python -m timeit -s " -from decorator import decorator - -@decorator -def do_nothing(func, *args, **kw): - return func(*args, **kw) - -@do_nothing -def f(): - pass -" "f()" - -python -m timeit -s " -def f(): - pass -" "f()" diff --git a/setup.py b/setup.py index 7269d1f..87f4568 100644 --- a/setup.py +++ b/setup.py @@ -2,24 +2,29 @@ try: from setuptools import setup except ImportError: from distutils.core import setup +import os.path -from decorator import __version__ as VERSION +def getversion(fname): + """Get the __version__ reading the file: works both in Python 2.X and 3.X, + whereas direct importing would break in Python 3.X with a syntax error""" + for line in open(fname): + if line.startswith('__version__'): + return eval(line[13:]) + raise NameError('Missing __version__ in decorator.py') + +VERSION = getversion( + os.path.join(os.path.dirname(__file__), 'src/decorator.py')) if __name__ == '__main__': - try: - docfile = file('/tmp/documentation.html') - except IOError: # file not found, ignore - doc = '' - else: - doc = docfile.read() setup(name='decorator', version=VERSION, description='Better living through Python with decorators', - long_description='
%s
' % doc,
+          long_description=open('README.txt').read(),
           author='Michele Simionato',
           author_email='michele.simionato@gmail.com',
           url='http://pypi.python.org/pypi/decorator',
           license="BSD License",
+          package_dir = {'': 'src'},
           py_modules = ['decorator'],
           keywords="decorators generic utility",
           platforms=["All"],
@@ -31,5 +36,5 @@ if __name__ == '__main__':
                        'Programming Language :: Python',
                        'Topic :: Software Development :: Libraries',
                        'Topic :: Utilities'],
+          use_2to3=True,
           zip_safe=False)
-
diff --git a/src/decorator.py b/src/decorator.py
new file mode 100644
index 0000000..9f0b21a
--- /dev/null
+++ b/src/decorator.py
@@ -0,0 +1,172 @@
+##########################     LICENCE     ###############################
+##
+##   Copyright (c) 2005, Michele Simionato
+##   All rights reserved.
+##
+##   Redistributions of source code must retain the above copyright 
+##   notice, this list of conditions and the following disclaimer.
+##   Redistributions in bytecode form must reproduce the above copyright
+##   notice, this list of conditions and the following disclaimer in
+##   the documentation and/or other materials provided with the
+##   distribution. 
+
+##   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+##   "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+##   LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+##   A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+##   HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+##   INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
+##   BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
+##   OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+##   ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
+##   TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
+##   USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
+##   DAMAGE.
+
+"""
+Decorator module, see http://pypi.python.org/pypi/decorator
+for the documentation.
+"""
+
+__version__ = '3.2.0'
+
+__all__ = ["decorator", "FunctionMaker", "partial"]
+
+import os, sys, re, inspect, string, warnings
+
+try:
+    from functools import partial
+except ImportError: # for Python version < 2.5
+    class partial(object):
+        "A simple replacement of functools.partial"
+        def __init__(self, func, *args, **kw):
+            self.func = func
+            self.args = args                
+            self.keywords = kw
+        def __call__(self, *otherargs, **otherkw):
+            kw = self.keywords.copy()
+            kw.update(otherkw)
+            return self.func(*(self.args + otherargs), **kw)
+
+DEF = re.compile('\s*def\s*([_\w][_\w\d]*)\s*\(')
+
+# basic functionality
+class FunctionMaker(object):
+    """
+    An object with the ability to create functions with a given signature.
+    It has attributes name, doc, module, signature, defaults, dict and
+    methods update and make.
+    """
+    def __init__(self, func=None, name=None, signature=None,
+                 defaults=None, doc=None, module=None, funcdict=None):
+        if func:
+            # func can be a class or a callable, but not an instance method
+            self.name = func.__name__
+            if self.name == '': # small hack for lambda functions
+                self.name = '_lambda_' 
+            self.doc = func.__doc__
+            self.module = func.__module__
+            if inspect.isfunction(func):
+                argspec = inspect.getargspec(func)
+                self.args, self.varargs, self.keywords, self.defaults = argspec
+                for i, arg in enumerate(self.args):
+                    setattr(self, 'arg%d' % i, arg)
+                self.signature = inspect.formatargspec(
+                    formatvalue=lambda val: "", *argspec)[1:-1]
+                self.dict = func.__dict__.copy()
+        if name:
+            self.name = name
+        if signature is not None:
+            self.signature = signature
+        if defaults:
+            self.defaults = defaults
+        if doc:
+            self.doc = doc
+        if module:
+            self.module = module
+        if funcdict:
+            self.dict = funcdict
+        # check existence required attributes
+        assert hasattr(self, 'name')
+        if not hasattr(self, 'signature'):
+            raise TypeError('You are decorating a non function: %s' % func)
+
+    def update(self, func, **kw):
+        "Update the signature of func with the data in self"
+        func.__name__ = self.name
+        func.__doc__ = getattr(self, 'doc', None)
+        func.__dict__ = getattr(self, 'dict', {})
+        func.func_defaults = getattr(self, 'defaults', ())
+        callermodule = sys._getframe(3).f_globals.get('__name__', '?')
+        func.__module__ = getattr(self, 'module', callermodule)
+        func.__dict__.update(kw)
+
+    def make(self, src_templ, evaldict=None, addsource=False, **attrs):
+        "Make a new function from a given template and update the signature"
+        src = src_templ % vars(self) # expand name and signature
+        evaldict = evaldict or {}
+        mo = DEF.match(src)
+        if mo is None:
+            raise SyntaxError('not a valid function template\n%s' % src)
+        name = mo.group(1) # extract the function name
+        reserved_names = set([name] + [
+            arg.strip(' *') for arg in self.signature.split(',')])
+        for n, v in evaldict.iteritems():
+            if n in reserved_names:
+                raise NameError('%s is overridden in\n%s' % (n, src))
+        if not src.endswith('\n'): # add a newline just for safety
+            src += '\n'
+        try:
+            code = compile(src, '', 'single')
+            exec code in evaldict
+        except:
+            print >> sys.stderr, 'Error in generated code:'
+            print >> sys.stderr, src
+            raise
+        func = evaldict[name]
+        if addsource:
+            attrs['__source__'] = src
+        self.update(func, **attrs)
+        return func
+
+    @classmethod
+    def create(cls, obj, body, evaldict, defaults=None,
+               doc=None, module=None, addsource=True,**attrs):
+        """
+        Create a function from the strings name, signature and body.
+        evaldict is the evaluation dictionary. If addsource is true an attribute
+        __source__ is added to the result. The attributes attrs are added,
+        if any.
+        """
+        if isinstance(obj, str): # "name(signature)"
+            name, rest = obj.strip().split('(', 1)
+            signature = rest[:-1] #strip a right parens            
+            func = None
+        else: # a function
+            name = None
+            signature = None
+            func = obj
+        fun = cls(func, name, signature, defaults, doc, module)
+        ibody = '\n'.join('    ' + line for line in body.splitlines())
+        return fun.make('def %(name)s(%(signature)s):\n' + ibody, 
+                        evaldict, addsource, **attrs)
+  
+def decorator(caller, func=None):
+    """
+    decorator(caller) converts a caller function into a decorator;
+    decorator(caller, func) decorates a function using a caller.
+    """
+    if func is not None: # returns a decorated function
+        return FunctionMaker.create(
+            func, "return _call_(_func_, %(signature)s)",
+            dict(_call_=caller, _func_=func), undecorated=func)
+    else: # returns a decorator
+        if isinstance(caller, partial):
+            return partial(decorator, caller)
+        # otherwise assume caller is a function
+        f = inspect.getargspec(caller)[0][0] # first arg
+        return FunctionMaker.create(
+            '%s(%s)' % (caller.__name__, f), 
+            'return decorator(_call_, %s)' % f,
+            dict(_call_=caller, decorator=decorator), undecorated=caller,
+            doc=caller.__doc__, module=caller.__module__)
-- 
cgit v1.2.1


From 42345d200ef0ca7cfd859dff15c4c383f65a8d2e Mon Sep 17 00:00:00 2001
From: micheles 
Date: Sat, 22 May 2010 10:03:23 +0200
Subject: Various improvements to the documentation

---
 CHANGES.txt         |    4 +-
 README.txt          |   44 +-
 documentation.html  |  394 +++---
 documentation.pdf   | 3829 +++++++++++++++++++++++++++++++++++++++++++++++++++
 documentation.py    |   22 +-
 documentation3.html |  392 +++---
 documentation3.pdf  | 3666 ++++++++++++++++++++++++++++++++++++++++++++++++
 documentation3.py   |   20 +-
 index.html          |   33 +-
 9 files changed, 8001 insertions(+), 403 deletions(-)
 create mode 100644 documentation.pdf
 create mode 100644 documentation3.pdf

diff --git a/CHANGES.txt b/CHANGES.txt
index 4e54d9b..0b75d2c 100644
--- a/CHANGES.txt
+++ b/CHANGES.txt
@@ -3,8 +3,8 @@ HISTORY
 
 3.2. Added __version__ (thanks to Gregg Lind), removed functionality which 
      has been deprecated for years, removed the confusing decorator_factory
-     example and added full support for Python 3 (thanks to Claus Klein)
-     (22/05/2010)
+     example and added official support for Python 3 (requested by Claus Klein).
+     Moved the documentation from PyPI to googlecode (22/05/2010)
 3.1.2. Added attributes args, varargs, keywords and arg0, ..., argN
      to FunctionMaker objects generated from a function; fixed another
      Pylons-breaking bug signaled by Lawrence Oluyede (25/08/2009)
diff --git a/README.txt b/README.txt
index 8469081..1fb5097 100644
--- a/README.txt
+++ b/README.txt
@@ -1,15 +1,32 @@
 Decorator module
----------------------------
+=================
 
 Dependencies:
 
 The decorator module requires Python 2.4.
 
-Installation:
+Installation
+-------------
+
+If you are lazy, just perform
+
+$ easy_install decorator
+
+which will install just the module on your system. Notice that
+Python 3 requires the easy_install version of the distribute_ project.
+
+If you prefer to install the full distribution from source, including
+the documentation, download the tarball_, unpack it and run
 
 $ python setup.py install
 
-Testing:
+in the main directory, possibly as superuser.
+
+.. _tarball: http://pypi.python.org/pypi/decorator
+.. _distribute: http://packages.python.org/distribute/
+
+Testing
+--------
 
 For Python 2.4, 2.5, 2.6, 2.7 run
 
@@ -22,16 +39,21 @@ $ python documentation3.py
 You will see a few innocuous errors with Python 2.4 and 2.5, because
 some inner details such as the introduction of the ArgSpec namedtuple 
 and Thread.__repr__ changed. You may safely ignore them.
+Notice that you may run into trouble if in your system there is an older version
+of the decorator module; in such a case remove the old version.
 
-Notice:
+Documentation
+--------------
 
-You may get into trouble if in your system there is an older version
-of the decorator module; in such a case remove the old version.
+There are various versions of the documentation:
 
-Documentation:
+-  `HTML version (Python 2)`_ 
+-  `PDF version (Python 2)`_ 
 
-There are two versions of the documentation, one for `Python 2`_ and one
-for `Python 3`_ .
+-  `HTML version (Python 3)`_ 
+-  `PDF version (Python 3)`_ 
 
-.. _Python 2: documentation.html
-.. _Python 3: documentation3.html
+.. _HTML version (Python 2): documentation.html
+.. _PDF version (Python 2): documentation.pdf
+.. _HTML version (Python 3): documentation3.html
+.. _PDF version (Python 3): documentation3.pdf
diff --git a/documentation.html b/documentation.html
index 2bca550..3a8160b 100644
--- a/documentation.html
+++ b/documentation.html
@@ -176,25 +176,27 @@ the function is called with the same input parameters the result is retrieved
 from the cache and not recomputed. There are many implementations of
 memoize in http://www.python.org/moin/PythonDecoratorLibrary,
 but they do not preserve the signature.
-A simple implementation for Python 2.5 could be the following (notice
+A simple implementation could be the following (notice
 that in general it is impossible to memoize correctly something
 that depends on non-hashable arguments):

-
-def memoize25(func):
-    func.cache = {}
-    def memoize(*args, **kw):
-        if kw: # frozenset is used to ensure hashability
-            key = args, frozenset(kw.iteritems())
-        else:
-            key = args
-        cache = func.cache
-        if key in cache:
-            return cache[key]
-        else:
-            cache[key] = result = func(*args, **kw)
-            return result
-    return functools.update_wrapper(memoize, func)
-
+
+
def memoize_uw(func):
+    func.cache = {}
+    def memoize(*args, **kw):
+        if kw: # frozenset is used to ensure hashability
+            key = args, frozenset(kw.iteritems())
+        else:
+            key = args
+        cache = func.cache
+        if key in cache:
+            return cache[key]
+        else:
+            cache[key] = result = func(*args, **kw)
+            return result
+    return functools.update_wrapper(memoize, func)
+
+ +

Here we used the functools.update_wrapper utility, which has been added in Python 2.5 expressly to simplify the definition of decorators (in older versions of Python you need to copy the function attributes @@ -203,11 +205,11 @@ from the original function to the decorated function by hand).

The implementation above works in the sense that the decorator can accept functions with generic signatures; unfortunately this implementation does not define a signature-preserving decorator, since in -general memoize25 returns a function with a +general memoize_uw returns a function with a different signature from the original function.

Consider for instance the following case:

-
>>> @memoize25
+
>>> @memoize_uw
 ... def f1(x):
 ...     time.sleep(1) # simulate some long computation
 ...     return x
@@ -219,7 +221,7 @@ but the decorated function takes any number of arguments and
 keyword arguments:

>>> from inspect import getargspec
->>> print getargspec(f1)
+>>> print getargspec(f1) # I am using Python 2.6+ here
 ArgSpec(args=[], varargs='args', keywords='kw', defaults=None)
 
@@ -255,26 +257,30 @@ returns the decorated function. The caller function must have signature (f, *args, **kw) and it must call the original function f with arguments args and kw, implementing the wanted capability, i.e. memoization in this case:

-
-def _memoize(func, *args, **kw):
-    if kw: # frozenset is used to ensure hashability
-        key = args, frozenset(kw.iteritems())
-    else:
-        key = args
-    cache = func.cache # attributed added by memoize
-    if key in cache:
-        return cache[key]
-    else:
-        cache[key] = result = func(*args, **kw)
-        return result
-
+
+
def _memoize(func, *args, **kw):
+    if kw: # frozenset is used to ensure hashability
+        key = args, frozenset(kw.iteritems())
+    else:
+        key = args
+    cache = func.cache # attributed added by memoize
+    if key in cache:
+        return cache[key]
+    else:
+        cache[key] = result = func(*args, **kw)
+        return result
+
+ +

At this point you can define your decorator as follows:

-
-def memoize(f):
-    f.cache = {}
-    return decorator(_memoize, f)
-
-

The difference with respect to the Python 2.5 approach, which is based +

+
def memoize(f):
+    f.cache = {}
+    return decorator(_memoize, f)
+
+ +
+

The difference with respect to the memoize_uw approach, which is based on nested functions, is that the decorator module forces you to lift the inner function at the outer level (flat is better than nested). Moreover, you are forced to pass explicitly the function you want to @@ -307,15 +313,19 @@ decorate to the caller function.

As an additional example, here is how you can define a trivial trace decorator, which prints a message everytime the traced function is called:

-
-def _trace(f, *args, **kw):
-    print "calling %s with args %s, %s" % (f.__name__, args, kw)
-    return f(*args, **kw)
-
-
-def trace(f):
-    return decorator(_trace, f)
-
+
+
def _trace(f, *args, **kw):
+    print "calling %s with args %s, %s" % (f.__name__, args, kw)
+    return f(*args, **kw)
+
+ +
+
+
def trace(f):
+    return decorator(_trace, f)
+
+ +

Here is an example of usage:

>>> @trace
@@ -419,21 +429,23 @@ object which can be used as a decorator:

sometimes it is best to have back a "busy" message than to block everything. This behavior can be implemented with a suitable family of decorators, where the parameter is the busy message:

-
-def blocking(not_avail):
-    def blocking(f, *args, **kw):
-        if not hasattr(f, "thread"): # no thread running
-            def set_result(): f.result = f(*args, **kw)
-            f.thread = threading.Thread(None, set_result)
-            f.thread.start()
-            return not_avail
-        elif f.thread.isAlive():
-            return not_avail
-        else: # the thread is ended, return the stored result
-            del f.thread
-            return f.result
-    return decorator(blocking)
-
+
+
def blocking(not_avail):
+    def blocking(f, *args, **kw):
+        if not hasattr(f, "thread"): # no thread running
+            def set_result(): f.result = f(*args, **kw)
+            f.thread = threading.Thread(None, set_result)
+            f.thread.start()
+            return not_avail
+        elif f.thread.isAlive():
+            return not_avail
+        else: # the thread is ended, return the stored result
+            del f.thread
+            return f.result
+    return decorator(blocking)
+
+ +

Functions decorated with blocking will return a busy message if the resource is unavailable, and the intended result if the resource is available. For instance:

@@ -478,58 +490,66 @@ is executed in a separate thread. Moreover, it is possible to set three callbacks on_success, on_failure and on_closing, to specify how to manage the function call. The implementation is the following:

-
-def on_success(result): # default implementation
-    "Called on the result of the function"
-    return result
-
-
-def on_failure(exc_info): # default implementation
-    "Called if the function fails"
-    pass
-
-
-def on_closing(): # default implementation
-    "Called at the end, both in case of success and failure"
-    pass
-
-
-class Async(object):
-    """
-    A decorator converting blocking functions into asynchronous
-    functions, by using threads or processes. Examples:
-
-    async_with_threads =  Async(threading.Thread)
-    async_with_processes =  Async(multiprocessing.Process)
-    """
-
-    def __init__(self, threadfactory):
-        self.threadfactory = threadfactory
-
-    def __call__(self, func, on_success=on_success,
-                 on_failure=on_failure, on_closing=on_closing):
-        # every decorated function has its own independent thread counter
-        func.counter = itertools.count(1)
-        func.on_success = on_success
-        func.on_failure = on_failure
-        func.on_closing = on_closing
-        return decorator(self.call, func)
-
-    def call(self, func, *args, **kw):
-        def func_wrapper():
-            try:
-                result = func(*args, **kw)
-            except:
-                func.on_failure(sys.exc_info())
-            else:
-                return func.on_success(result)
-            finally:
-                func.on_closing()
-        name = '%s-%s' % (func.__name__, func.counter.next())
-        thread = self.threadfactory(None, func_wrapper, name)
-        thread.start()
-        return thread
-
+
+
def on_success(result): # default implementation
+    "Called on the result of the function"
+    return result
+
+ +
+
+
def on_failure(exc_info): # default implementation
+    "Called if the function fails"
+    pass
+
+ +
+
+
def on_closing(): # default implementation
+    "Called at the end, both in case of success and failure"
+    pass
+
+ +
+
+
class Async(object):
+    """
+    A decorator converting blocking functions into asynchronous
+    functions, by using threads or processes. Examples:
+
+    async_with_threads =  Async(threading.Thread)
+    async_with_processes =  Async(multiprocessing.Process)
+    """
+
+    def __init__(self, threadfactory):
+        self.threadfactory = threadfactory
+
+    def __call__(self, func, on_success=on_success,
+                 on_failure=on_failure, on_closing=on_closing):
+        # every decorated function has its own independent thread counter
+        func.counter = itertools.count(1)
+        func.on_success = on_success
+        func.on_failure = on_failure
+        func.on_closing = on_closing
+        return decorator(self.call, func)
+
+    def call(self, func, *args, **kw):
+        def func_wrapper():
+            try:
+                result = func(*args, **kw)
+            except:
+                func.on_failure(sys.exc_info())
+            else:
+                return func.on_success(result)
+            finally:
+                func.on_closing()
+        name = '%s-%s' % (func.__name__, func.counter.next())
+        thread = self.threadfactory(None, func_wrapper, name)
+        thread.start()
+        return thread
+
+ +

The decorated function returns the current execution thread, which can be stored and checked later, for instance to verify that the thread .isAlive().

@@ -654,12 +674,14 @@ available. In the past I have considered this acceptable, since inspect.getsource does not really work even with regular decorators. In that case inspect.getsource gives you the wrapper source code which is probably not what you want:

-
-def identity_dec(func):
-    def wrapper(*args, **kw):
-        return func(*args, **kw)
-    return wrapper
-
+
+
def identity_dec(func):
+    def wrapper(*args, **kw):
+        return func(*args, **kw)
+    return wrapper
+
+ +
@identity_dec
 def example(): pass
@@ -698,16 +720,18 @@ decorator is not signature-preserving. Therefore you may want an easy way to
 upgrade third party decorators to signature-preserving decorators without
 having to rewrite them in terms of decorator. You can use a
 FunctionMaker to implement that functionality as follows:

-
-def decorator_apply(dec, func):
-    """
-    Decorate a function by preserving the signature even if dec
-    is not a signature-preserving decorator.
-    """
-    return FunctionMaker.create(
-        func, 'return decorated(%(signature)s)',
-        dict(decorated=dec(func)), undecorated=func)
-
+
+
def decorator_apply(dec, func):
+    """
+    Decorate a function by preserving the signature even if dec
+    is not a signature-preserving decorator.
+    """
+    return FunctionMaker.create(
+        func, 'return decorated(%(signature)s)',
+        dict(decorated=dec(func)), undecorated=func)
+
+ +

decorator_apply sets the attribute .undecorated of the generated function to the original function, so that you can get the right source code.

@@ -721,51 +745,57 @@ pretty slick decorator that converts a tail-recursive function in an iterative function. I have shamelessly stolen the basic idea from Kay Schluehr's recipe in the Python Cookbook, http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/496691.

-
-class TailRecursive(object):
-    """
-    tail_recursive decorator based on Kay Schluehr's recipe
-    http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/496691
-    with improvements by me and George Sakkis.
-    """
-
-    def __init__(self, func):
-        self.func = func
-        self.firstcall = True
-        self.CONTINUE = object() # sentinel
-
-    def __call__(self, *args, **kwd):
-        CONTINUE = self.CONTINUE
-        if self.firstcall:
-            func = self.func
-            self.firstcall = False
-            try:
-                while True:
-                    result = func(*args, **kwd)
-                    if result is CONTINUE: # update arguments
-                        args, kwd = self.argskwd
-                    else: # last call
-                        return result
-            finally:
-                self.firstcall = True
-        else: # return the arguments of the tail call
-            self.argskwd = args, kwd
-            return CONTINUE
-
+
+
class TailRecursive(object):
+    """
+    tail_recursive decorator based on Kay Schluehr's recipe
+    http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/496691
+    with improvements by me and George Sakkis.
+    """
+
+    def __init__(self, func):
+        self.func = func
+        self.firstcall = True
+        self.CONTINUE = object() # sentinel
+
+    def __call__(self, *args, **kwd):
+        CONTINUE = self.CONTINUE
+        if self.firstcall:
+            func = self.func
+            self.firstcall = False
+            try:
+                while True:
+                    result = func(*args, **kwd)
+                    if result is CONTINUE: # update arguments
+                        args, kwd = self.argskwd
+                    else: # last call
+                        return result
+            finally:
+                self.firstcall = True
+        else: # return the arguments of the tail call
+            self.argskwd = args, kwd
+            return CONTINUE
+
+ +

Here the decorator is implemented as a class returning callable objects.

-
-def tail_recursive(func):
-    return decorator_apply(TailRecursive, func)
-
+
+
def tail_recursive(func):
+    return decorator_apply(TailRecursive, func)
+
+ +

Here is how you apply the upgraded decorator to the good old factorial:

-
-@tail_recursive
-def factorial(n, acc=1):
-    "The good old factorial"
-    if n == 0: return acc
-    return factorial(n-1, n*acc)
-
+
+
@tail_recursive
+def factorial(n, acc=1):
+    "The good old factorial"
+    if n == 0: return acc
+    return factorial(n-1, n*acc)
+
+ +
>>> print factorial(4)
 24
@@ -777,11 +807,13 @@ your mind ;) Notice that there is no recursion limit now, and you can
 easily compute factorial(1001) or larger without filling the stack
 frame. Notice also that the decorator will not work on functions which
 are not tail recursive, such as the following

-
-def fact(n): # this is not tail-recursive
-    if n == 0: return 1
-    return n * fact(n-1)
-
+
+
def fact(n): # this is not tail-recursive
+    if n == 0: return 1
+    return n * fact(n-1)
+
+ +

(reminder: a function is tail recursive if it either returns a value without making a recursive call, or returns directly the result of a recursive call).

@@ -940,7 +972,7 @@ the beginning, via the 2to3 conversion tool, b been now integrated in the build process, thanks to the distribute project, the Python 3-compatible replacement of easy_install. The hard work (for me) has been converting the documentation and the -doctests. This has been possibly only now that docutils and pygments +doctests. This has been possible only now that docutils and pygments have been ported to Python 3.

The decorator module per se does not contain any change, apart from the removal of the functions get_info and new_wrapper, @@ -968,11 +1000,11 @@ downgrade to the 2.3 version.

The examples shown here have been tested with Python 2.6. Python 2.4 is also supported - of course the examples requiring the with statement will not work there. Python 2.5 works fine, but if you -run the examples here in the interactive interpreter +run the examples in the interactive interpreter you will notice a few differences since getargspec returns an ArgSpec namedtuple instead of a regular tuple. That means that running the file -documentation.py under Python 2.5 will a few errors, but +documentation.py under Python 2.5 will print a few errors, but they are not serious.

diff --git a/documentation.pdf b/documentation.pdf new file mode 100644 index 0000000..401c867 --- /dev/null +++ b/documentation.pdf @@ -0,0 +1,3829 @@ +%PDF-1.3 +%“Œ‹ž ReportLab Generated PDF document http://www.reportlab.com +% 'BasicFonts': class PDFDictionary +1 0 obj +% The standard fonts dictionary +<< /F1 2 0 R + /F2 3 0 R + /F3 4 0 R + /F4 5 0 R + /F5 8 0 R + /F6 38 0 R + /F7 40 0 R >> +endobj +% 'F1': class PDFType1Font +2 0 obj +% Font Helvetica +<< /BaseFont /Helvetica + /Encoding /WinAnsiEncoding + /Name /F1 + /Subtype /Type1 + /Type /Font >> +endobj +% 'F2': class PDFType1Font +3 0 obj +% Font Helvetica-Bold +<< /BaseFont /Helvetica-Bold + /Encoding /WinAnsiEncoding + /Name /F2 + /Subtype /Type1 + /Type /Font >> +endobj +% 'F3': class PDFType1Font +4 0 obj +% Font Courier-Bold +<< /BaseFont /Courier-Bold + /Encoding /WinAnsiEncoding + /Name /F3 + /Subtype /Type1 + /Type /Font >> +endobj +% 'F4': class PDFType1Font +5 0 obj +% Font Times-Roman +<< /BaseFont /Times-Roman + /Encoding /WinAnsiEncoding + /Name /F4 + /Subtype /Type1 + /Type /Font >> +endobj +% 'Annot.NUMBER1': class PDFDictionary +6 0 obj +<< /A << /S /URI + /Type /Action + /URI (mailto:michele.simionato@gmail.com) >> + /Border [ 0 + 0 + 0 ] + /Rect [ 153.7323 + 707.5936 + 526.5827 + 719.5936 ] + /Subtype /Link + /Type /Annot >> +endobj +% 'Annot.NUMBER2': class PDFDictionary +7 0 obj +<< /A << /S /URI + /Type /Action + /URI (http://pypi.python.org/pypi/decorator/3.2.0) >> + /Border [ 0 + 0 + 0 ] + /Rect [ 153.7323 + 662.5936 + 526.5827 + 674.5936 ] + /Subtype /Link + /Type /Annot >> +endobj +% 'F5': class PDFType1Font +8 0 obj +% Font Courier +<< /BaseFont /Courier + /Encoding /WinAnsiEncoding + /Name /F5 + /Subtype /Type1 + /Type /Font >> +endobj +% 'Annot.NUMBER3': class LinkAnnotation +9 0 obj +<< /Border [ 0 + 0 + 0 ] + /Contents () + /Dest [ 37 0 R + /XYZ + 62.69291 + 311.0236 + 0 ] + /Rect [ 62.69291 + 563.5936 + 121.0229 + 575.5936 ] + /Subtype /Link + /Type /Annot >> +endobj +% 'Annot.NUMBER4': class LinkAnnotation +10 0 obj +<< /Border [ 0 + 0 + 0 ] + /Contents () + /Dest [ 37 0 R + /XYZ + 62.69291 + 311.0236 + 0 ] + /Rect [ 527.0227 + 563.5936 + 532.5827 + 575.5936 ] + /Subtype /Link + /Type /Annot >> +endobj +% 'Annot.NUMBER5': class LinkAnnotation +11 0 obj +<< /Border [ 0 + 0 + 0 ] + /Contents () + /Dest [ 42 0 R + /XYZ + 62.69291 + 675.0236 + 0 ] + /Rect [ 62.69291 + 545.5936 + 114.3629 + 557.5936 ] + /Subtype /Link + /Type /Annot >> +endobj +% 'Annot.NUMBER6': class LinkAnnotation +12 0 obj +<< /Border [ 0 + 0 + 0 ] + /Contents () + /Dest [ 42 0 R + /XYZ + 62.69291 + 675.0236 + 0 ] + /Rect [ 527.0227 + 545.5936 + 532.5827 + 557.5936 ] + /Subtype /Link + /Type /Annot >> +endobj +% 'Annot.NUMBER7': class LinkAnnotation +13 0 obj +<< /Border [ 0 + 0 + 0 ] + /Contents () + /Dest [ 42 0 R + /XYZ + 62.69291 + 432.0236 + 0 ] + /Rect [ 62.69291 + 527.5936 + 183.2629 + 539.5936 ] + /Subtype /Link + /Type /Annot >> +endobj +% 'Annot.NUMBER8': class LinkAnnotation +14 0 obj +<< /Border [ 0 + 0 + 0 ] + /Contents () + /Dest [ 42 0 R + /XYZ + 62.69291 + 432.0236 + 0 ] + /Rect [ 527.0227 + 527.5936 + 532.5827 + 539.5936 ] + /Subtype /Link + /Type /Annot >> +endobj +% 'Annot.NUMBER9': class LinkAnnotation +15 0 obj +<< /Border [ 0 + 0 + 0 ] + /Contents () + /Dest [ 43 0 R + /XYZ + 62.69291 + 427.4236 + 0 ] + /Rect [ 62.69291 + 509.5936 + 122.1429 + 521.5936 ] + /Subtype /Link + /Type /Annot >> +endobj +% 'Annot.NUMBER10': class LinkAnnotation +16 0 obj +<< /Border [ 0 + 0 + 0 ] + /Contents () + /Dest [ 43 0 R + /XYZ + 62.69291 + 427.4236 + 0 ] + /Rect [ 527.0227 + 509.5936 + 532.5827 + 521.5936 ] + /Subtype /Link + /Type /Annot >> +endobj +% 'Annot.NUMBER11': class LinkAnnotation +17 0 obj +<< /Border [ 0 + 0 + 0 ] + /Contents () + /Dest [ 44 0 R + /XYZ + 62.69291 + 435.4236 + 0 ] + /Rect [ 62.69291 + 491.5936 + 154.8129 + 503.5936 ] + /Subtype /Link + /Type /Annot >> +endobj +% 'Annot.NUMBER12': class LinkAnnotation +18 0 obj +<< /Border [ 0 + 0 + 0 ] + /Contents () + /Dest [ 44 0 R + /XYZ + 62.69291 + 435.4236 + 0 ] + /Rect [ 527.0227 + 491.5936 + 532.5827 + 503.5936 ] + /Subtype /Link + /Type /Annot >> +endobj +% 'Annot.NUMBER13': class LinkAnnotation +19 0 obj +<< /Border [ 0 + 0 + 0 ] + /Contents () + /Dest [ 45 0 R + /XYZ + 62.69291 + 398.778 + 0 ] + /Rect [ 62.69291 + 473.5936 + 188.2729 + 485.5936 ] + /Subtype /Link + /Type /Annot >> +endobj +% 'Annot.NUMBER14': class LinkAnnotation +20 0 obj +<< /Border [ 0 + 0 + 0 ] + /Contents () + /Dest [ 45 0 R + /XYZ + 62.69291 + 398.778 + 0 ] + /Rect [ 527.0227 + 473.5936 + 532.5827 + 485.5936 ] + /Subtype /Link + /Type /Annot >> +endobj +% 'Annot.NUMBER15': class LinkAnnotation +21 0 obj +<< /Border [ 0 + 0 + 0 ] + /Contents () + /Dest [ 46 0 R + /XYZ + 62.69291 + 647.8236 + 0 ] + /Rect [ 62.69291 + 455.5936 + 110.6929 + 467.5936 ] + /Subtype /Link + /Type /Annot >> +endobj +% 'Annot.NUMBER16': class LinkAnnotation +22 0 obj +<< /Border [ 0 + 0 + 0 ] + /Contents () + /Dest [ 46 0 R + /XYZ + 62.69291 + 647.8236 + 0 ] + /Rect [ 527.0227 + 455.5936 + 532.5827 + 467.5936 ] + /Subtype /Link + /Type /Annot >> +endobj +% 'Annot.NUMBER17': class LinkAnnotation +23 0 obj +<< /Border [ 0 + 0 + 0 ] + /Contents () + /Dest [ 47 0 R + /XYZ + 62.69291 + 765.0236 + 0 ] + /Rect [ 62.69291 + 437.5936 + 92.69291 + 449.5936 ] + /Subtype /Link + /Type /Annot >> +endobj +% 'Annot.NUMBER18': class LinkAnnotation +24 0 obj +<< /Border [ 0 + 0 + 0 ] + /Contents () + /Dest [ 47 0 R + /XYZ + 62.69291 + 765.0236 + 0 ] + /Rect [ 527.0227 + 437.5936 + 532.5827 + 449.5936 ] + /Subtype /Link + /Type /Annot >> +endobj +% 'Annot.NUMBER19': class LinkAnnotation +25 0 obj +<< /Border [ 0 + 0 + 0 ] + /Contents () + /Dest [ 48 0 R + /XYZ + 62.69291 + 243.4236 + 0 ] + /Rect [ 62.69291 + 419.5936 + 192.2729 + 431.5936 ] + /Subtype /Link + /Type /Annot >> +endobj +% 'Annot.NUMBER20': class LinkAnnotation +26 0 obj +<< /Border [ 0 + 0 + 0 ] + /Contents () + /Dest [ 48 0 R + /XYZ + 62.69291 + 243.4236 + 0 ] + /Rect [ 527.0227 + 419.5936 + 532.5827 + 431.5936 ] + /Subtype /Link + /Type /Annot >> +endobj +% 'Annot.NUMBER21': class LinkAnnotation +27 0 obj +<< /Border [ 0 + 0 + 0 ] + /Contents () + /Dest [ 49 0 R + /XYZ + 62.69291 + 240.6236 + 0 ] + /Rect [ 62.69291 + 401.5936 + 177.1629 + 413.5936 ] + /Subtype /Link + /Type /Annot >> +endobj +% 'Annot.NUMBER22': class LinkAnnotation +28 0 obj +<< /Border [ 0 + 0 + 0 ] + /Contents () + /Dest [ 49 0 R + /XYZ + 62.69291 + 240.6236 + 0 ] + /Rect [ 527.0227 + 401.5936 + 532.5827 + 413.5936 ] + /Subtype /Link + /Type /Annot >> +endobj +% 'Annot.NUMBER23': class LinkAnnotation +29 0 obj +<< /Border [ 0 + 0 + 0 ] + /Contents () + /Dest [ 52 0 R + /XYZ + 62.69291 + 461.4236 + 0 ] + /Rect [ 62.69291 + 383.5936 + 228.2829 + 395.5936 ] + /Subtype /Link + /Type /Annot >> +endobj +% 'Annot.NUMBER24': class LinkAnnotation +30 0 obj +<< /Border [ 0 + 0 + 0 ] + /Contents () + /Dest [ 52 0 R + /XYZ + 62.69291 + 461.4236 + 0 ] + /Rect [ 521.4627 + 383.5936 + 532.5827 + 395.5936 ] + /Subtype /Link + /Type /Annot >> +endobj +% 'Annot.NUMBER25': class LinkAnnotation +31 0 obj +<< /Border [ 0 + 0 + 0 ] + /Contents () + /Dest [ 54 0 R + /XYZ + 62.69291 + 765.0236 + 0 ] + /Rect [ 62.69291 + 365.5936 + 174.3929 + 377.5936 ] + /Subtype /Link + /Type /Annot >> +endobj +% 'Annot.NUMBER26': class LinkAnnotation +32 0 obj +<< /Border [ 0 + 0 + 0 ] + /Contents () + /Dest [ 54 0 R + /XYZ + 62.69291 + 765.0236 + 0 ] + /Rect [ 521.4627 + 365.5936 + 532.5827 + 377.5936 ] + /Subtype /Link + /Type /Annot >> +endobj +% 'Annot.NUMBER27': class LinkAnnotation +33 0 obj +<< /Border [ 0 + 0 + 0 ] + /Contents () + /Dest [ 62 0 R + /XYZ + 62.69291 + 607.8236 + 0 ] + /Rect [ 62.69291 + 347.5936 + 155.4829 + 359.5936 ] + /Subtype /Link + /Type /Annot >> +endobj +% 'Annot.NUMBER28': class LinkAnnotation +34 0 obj +<< /Border [ 0 + 0 + 0 ] + /Contents () + /Dest [ 62 0 R + /XYZ + 62.69291 + 607.8236 + 0 ] + /Rect [ 521.4627 + 347.5936 + 532.5827 + 359.5936 ] + /Subtype /Link + /Type /Annot >> +endobj +% 'Annot.NUMBER29': class LinkAnnotation +35 0 obj +<< /Border [ 0 + 0 + 0 ] + /Contents () + /Dest [ 62 0 R + /XYZ + 62.69291 + 232.8236 + 0 ] + /Rect [ 62.69291 + 329.5936 + 106.5829 + 341.5936 ] + /Subtype /Link + /Type /Annot >> +endobj +% 'Annot.NUMBER30': class LinkAnnotation +36 0 obj +<< /Border [ 0 + 0 + 0 ] + /Contents () + /Dest [ 62 0 R + /XYZ + 62.69291 + 232.8236 + 0 ] + /Rect [ 521.4627 + 329.5936 + 532.5827 + 341.5936 ] + /Subtype /Link + /Type /Annot >> +endobj +% 'Page1': class PDFPage +37 0 obj +% Page dictionary +<< /Annots [ 6 0 R + 7 0 R + 9 0 R + 10 0 R + 11 0 R + 12 0 R + 13 0 R + 14 0 R + 15 0 R + 16 0 R + 17 0 R + 18 0 R + 19 0 R + 20 0 R + 21 0 R + 22 0 R + 23 0 R + 24 0 R + 25 0 R + 26 0 R + 27 0 R + 28 0 R + 29 0 R + 30 0 R + 31 0 R + 32 0 R + 33 0 R + 34 0 R + 35 0 R + 36 0 R ] + /Contents 82 0 R + /MediaBox [ 0 + 0 + 595.2756 + 841.8898 ] + /Parent 81 0 R + /Resources << /Font 1 0 R + /ProcSet [ /PDF + /Text + /ImageB + /ImageC + /ImageI ] >> + /Rotate 0 + /Trans << >> + /Type /Page >> +endobj +% 'F6': class PDFType1Font +38 0 obj +% Font Helvetica-Oblique +<< /BaseFont /Helvetica-Oblique + /Encoding /WinAnsiEncoding + /Name /F6 + /Subtype /Type1 + /Type /Font >> +endobj +% 'Annot.NUMBER31': class PDFDictionary +39 0 obj +<< /A << /S /URI + /Type /Action + /URI (http://www.python.org/moin/PythonDecoratorLibrary) >> + /Border [ 0 + 0 + 0 ] + /Rect [ 219.6428 + 360.5936 + 449.1728 + 372.5936 ] + /Subtype /Link + /Type /Annot >> +endobj +% 'F7': class PDFType1Font +40 0 obj +% Font Courier-Oblique +<< /BaseFont /Courier-Oblique + /Encoding /WinAnsiEncoding + /Name /F7 + /Subtype /Type1 + /Type /Font >> +endobj +% 'Annot.NUMBER32': class PDFDictionary +41 0 obj +<< /A << /S /URI + /Type /Action + /URI (http://www.python.org/doc/2.5.2/lib/module-functools.html) >> + /Border [ 0 + 0 + 0 ] + /Rect [ 151.0486 + 127.3936 + 270.69 + 139.3936 ] + /Subtype /Link + /Type /Annot >> +endobj +% 'Page2': class PDFPage +42 0 obj +% Page dictionary +<< /Annots [ 39 0 R + 41 0 R ] + /Contents 83 0 R + /MediaBox [ 0 + 0 + 595.2756 + 841.8898 ] + /Parent 81 0 R + /Resources << /Font 1 0 R + /ProcSet [ /PDF + /Text + /ImageB + /ImageC + /ImageI ] >> + /Rotate 0 + /Trans << >> + /Type /Page >> +endobj +% 'Page3': class PDFPage +43 0 obj +% Page dictionary +<< /Contents 84 0 R + /MediaBox [ 0 + 0 + 595.2756 + 841.8898 ] + /Parent 81 0 R + /Resources << /Font 1 0 R + /ProcSet [ /PDF + /Text + /ImageB + /ImageC + /ImageI ] >> + /Rotate 0 + /Trans << >> + /Type /Page >> +endobj +% 'Page4': class PDFPage +44 0 obj +% Page dictionary +<< /Contents 85 0 R + /MediaBox [ 0 + 0 + 595.2756 + 841.8898 ] + /Parent 81 0 R + /Resources << /Font 1 0 R + /ProcSet [ /PDF + /Text + /ImageB + /ImageC + /ImageI ] >> + /Rotate 0 + /Trans << >> + /Type /Page >> +endobj +% 'Page5': class PDFPage +45 0 obj +% Page dictionary +<< /Contents 86 0 R + /MediaBox [ 0 + 0 + 595.2756 + 841.8898 ] + /Parent 81 0 R + /Resources << /Font 1 0 R + /ProcSet [ /PDF + /Text + /ImageB + /ImageC + /ImageI ] >> + /Rotate 0 + /Trans << >> + /Type /Page >> +endobj +% 'Page6': class PDFPage +46 0 obj +% Page dictionary +<< /Contents 87 0 R + /MediaBox [ 0 + 0 + 595.2756 + 841.8898 ] + /Parent 81 0 R + /Resources << /Font 1 0 R + /ProcSet [ /PDF + /Text + /ImageB + /ImageC + /ImageI ] >> + /Rotate 0 + /Trans << >> + /Type /Page >> +endobj +% 'Page7': class PDFPage +47 0 obj +% Page dictionary +<< /Contents 88 0 R + /MediaBox [ 0 + 0 + 595.2756 + 841.8898 ] + /Parent 81 0 R + /Resources << /Font 1 0 R + /ProcSet [ /PDF + /Text + /ImageB + /ImageC + /ImageI ] >> + /Rotate 0 + /Trans << >> + /Type /Page >> +endobj +% 'Page8': class PDFPage +48 0 obj +% Page dictionary +<< /Contents 89 0 R + /MediaBox [ 0 + 0 + 595.2756 + 841.8898 ] + /Parent 81 0 R + /Resources << /Font 1 0 R + /ProcSet [ /PDF + /Text + /ImageB + /ImageC + /ImageI ] >> + /Rotate 0 + /Trans << >> + /Type /Page >> +endobj +% 'Page9': class PDFPage +49 0 obj +% Page dictionary +<< /Contents 90 0 R + /MediaBox [ 0 + 0 + 595.2756 + 841.8898 ] + /Parent 81 0 R + /Resources << /Font 1 0 R + /ProcSet [ /PDF + /Text + /ImageB + /ImageC + /ImageI ] >> + /Rotate 0 + /Trans << >> + /Type /Page >> +endobj +% 'Annot.NUMBER33': class PDFDictionary +50 0 obj +<< /A << /S /URI + /Type /Action + /URI (http://bugs.python.org/issue1764286) >> + /Border [ 0 + 0 + 0 ] + /Rect [ 137.6966 + 618.1936 + 180.8679 + 630.1936 ] + /Subtype /Link + /Type /Annot >> +endobj +% 'Annot.NUMBER34': class PDFDictionary +51 0 obj +<< /A << /S /URI + /Type /Action + /URI (http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/496691) >> + /Border [ 0 + 0 + 0 ] + /Rect [ 62.69291 + 144.7936 + 363.4029 + 156.7936 ] + /Subtype /Link + /Type /Annot >> +endobj +% 'Page10': class PDFPage +52 0 obj +% Page dictionary +<< /Annots [ 50 0 R + 51 0 R ] + /Contents 91 0 R + /MediaBox [ 0 + 0 + 595.2756 + 841.8898 ] + /Parent 81 0 R + /Resources << /Font 1 0 R + /ProcSet [ /PDF + /Text + /ImageB + /ImageC + /ImageI ] >> + /Rotate 0 + /Trans << >> + /Type /Page >> +endobj +% 'Page11': class PDFPage +53 0 obj +% Page dictionary +<< /Contents 92 0 R + /MediaBox [ 0 + 0 + 595.2756 + 841.8898 ] + /Parent 81 0 R + /Resources << /Font 1 0 R + /ProcSet [ /PDF + /Text + /ImageB + /ImageC + /ImageI ] >> + /Rotate 0 + /Trans << >> + /Type /Page >> +endobj +% 'Page12': class PDFPage +54 0 obj +% Page dictionary +<< /Contents 93 0 R + /MediaBox [ 0 + 0 + 595.2756 + 841.8898 ] + /Parent 81 0 R + /Resources << /Font 1 0 R + /ProcSet [ /PDF + /Text + /ImageB + /ImageC + /ImageI ] >> + /Rotate 0 + /Trans << >> + /Type /Page >> +endobj +% 'Annot.NUMBER35': class PDFDictionary +55 0 obj +<< /A << /S /URI + /Type /Action + /URI (http://www.python.org/dev/peps/pep-0362) >> + /Border [ 0 + 0 + 0 ] + /Rect [ 301.1597 + 666.5936 + 317.8397 + 678.5936 ] + /Subtype /Link + /Type /Annot >> +endobj +% 'Page13': class PDFPage +56 0 obj +% Page dictionary +<< /Annots [ 55 0 R ] + /Contents 94 0 R + /MediaBox [ 0 + 0 + 595.2756 + 841.8898 ] + /Parent 81 0 R + /Resources << /Font 1 0 R + /ProcSet [ /PDF + /Text + /ImageB + /ImageC + /ImageI ] >> + /Rotate 0 + /Trans << >> + /Type /Page >> +endobj +% 'Annot.NUMBER36': class PDFDictionary +57 0 obj +<< /A << /S /URI + /Type /Action + /URI (http://packages.python.org/distribute/) >> + /Border [ 0 + 0 + 0 ] + /Rect [ 334.9756 + 548.3936 + 381.0399 + 560.3936 ] + /Subtype /Link + /Type /Annot >> +endobj +% 'Annot.NUMBER37': class PDFDictionary +58 0 obj +<< /A << /S /URI + /Type /Action + /URI (http://docutils.sourceforge.net/) >> + /Border [ 0 + 0 + 0 ] + /Rect [ 272.2429 + 524.3936 + 308.9229 + 536.3936 ] + /Subtype /Link + /Type /Annot >> +endobj +% 'Annot.NUMBER38': class PDFDictionary +59 0 obj +<< /A << /S /URI + /Type /Action + /URI (http://pygments.org/) >> + /Border [ 0 + 0 + 0 ] + /Rect [ 328.3829 + 524.3936 + 374.5129 + 536.3936 ] + /Subtype /Link + /Type /Annot >> +endobj +% 'Annot.NUMBER39': class PDFDictionary +60 0 obj +<< /A << /S /URI + /Type /Action + /URI (http://www.python.org/dev/peps/pep-3107/) >> + /Border [ 0 + 0 + 0 ] + /Rect [ 62.69291 + 392.3936 + 157.3009 + 404.3936 ] + /Subtype /Link + /Type /Annot >> +endobj +% 'Annot.NUMBER40': class PDFDictionary +61 0 obj +<< /A << /S /URI + /Type /Action + /URI (http://www.phyast.pitt.edu/~micheles/python/documentation.html#class-decorators-and-decorator-factories) >> + /Border [ 0 + 0 + 0 ] + /Rect [ 364.2921 + 362.3936 + 531.64 + 374.3936 ] + /Subtype /Link + /Type /Annot >> +endobj +% 'Page14': class PDFPage +62 0 obj +% Page dictionary +<< /Annots [ 57 0 R + 58 0 R + 59 0 R + 60 0 R + 61 0 R ] + /Contents 95 0 R + /MediaBox [ 0 + 0 + 595.2756 + 841.8898 ] + /Parent 81 0 R + /Resources << /Font 1 0 R + /ProcSet [ /PDF + /Text + /ImageB + /ImageC + /ImageI ] >> + /Rotate 0 + /Trans << >> + /Type /Page >> +endobj +% 'Page15': class PDFPage +63 0 obj +% Page dictionary +<< /Contents 96 0 R + /MediaBox [ 0 + 0 + 595.2756 + 841.8898 ] + /Parent 81 0 R + /Resources << /Font 1 0 R + /ProcSet [ /PDF + /Text + /ImageB + /ImageC + /ImageI ] >> + /Rotate 0 + /Trans << >> + /Type /Page >> +endobj +% 'R64': class PDFCatalog +64 0 obj +% Document Root +<< /Outlines 66 0 R + /PageLabels 97 0 R + /PageMode /UseNone + /Pages 81 0 R + /Type /Catalog >> +endobj +% 'R65': class PDFInfo +65 0 obj +<< /Author (Michele Simionato) + /CreationDate (D:20100522100028-01'00') + /Keywords () + /Producer (ReportLab http://www.reportlab.com) + /Subject (\(unspecified\)) + /Title (The decorator module) >> +endobj +% 'R66': class PDFOutlines +66 0 obj +<< /Count 14 + /First 67 0 R + /Last 80 0 R + /Type /Outlines >> +endobj +% 'Outline.0': class OutlineEntryObject +67 0 obj +<< /Dest [ 37 0 R + /XYZ + 62.69291 + 311.0236 + 0 ] + /Next 68 0 R + /Parent 66 0 R + /Title (Introduction) >> +endobj +% 'Outline.1': class OutlineEntryObject +68 0 obj +<< /Dest [ 42 0 R + /XYZ + 62.69291 + 675.0236 + 0 ] + /Next 69 0 R + /Parent 66 0 R + /Prev 67 0 R + /Title (Definitions) >> +endobj +% 'Outline.2': class OutlineEntryObject +69 0 obj +<< /Dest [ 42 0 R + /XYZ + 62.69291 + 432.0236 + 0 ] + /Next 70 0 R + /Parent 66 0 R + /Prev 68 0 R + /Title (Statement of the problem) >> +endobj +% 'Outline.3': class OutlineEntryObject +70 0 obj +<< /Dest [ 43 0 R + /XYZ + 62.69291 + 427.4236 + 0 ] + /Next 71 0 R + /Parent 66 0 R + /Prev 69 0 R + /Title (The solution) >> +endobj +% 'Outline.4': class OutlineEntryObject +71 0 obj +<< /Dest [ 44 0 R + /XYZ + 62.69291 + 435.4236 + 0 ] + /Next 72 0 R + /Parent 66 0 R + /Prev 70 0 R + /Title (A trace decorator) >> +endobj +% 'Outline.5': class OutlineEntryObject +72 0 obj +<< /Dest [ 45 0 R + /XYZ + 62.69291 + 398.778 + 0 ] + /Next 73 0 R + /Parent 66 0 R + /Prev 71 0 R + /Title (decorator is a decorator) >> +endobj +% 'Outline.6': class OutlineEntryObject +73 0 obj +<< /Dest [ 46 0 R + /XYZ + 62.69291 + 647.8236 + 0 ] + /Next 74 0 R + /Parent 66 0 R + /Prev 72 0 R + /Title (blocking) >> +endobj +% 'Outline.7': class OutlineEntryObject +74 0 obj +<< /Dest [ 47 0 R + /XYZ + 62.69291 + 765.0236 + 0 ] + /Next 75 0 R + /Parent 66 0 R + /Prev 73 0 R + /Title (async) >> +endobj +% 'Outline.8': class OutlineEntryObject +75 0 obj +<< /Dest [ 48 0 R + /XYZ + 62.69291 + 243.4236 + 0 ] + /Next 76 0 R + /Parent 66 0 R + /Prev 74 0 R + /Title (The FunctionMaker class) >> +endobj +% 'Outline.9': class OutlineEntryObject +76 0 obj +<< /Dest [ 49 0 R + /XYZ + 62.69291 + 240.6236 + 0 ] + /Next 77 0 R + /Parent 66 0 R + /Prev 75 0 R + /Title (Getting the source code) >> +endobj +% 'Outline.10': class OutlineEntryObject +77 0 obj +<< /Dest [ 52 0 R + /XYZ + 62.69291 + 461.4236 + 0 ] + /Next 78 0 R + /Parent 66 0 R + /Prev 76 0 R + /Title (Dealing with third party decorators) >> +endobj +% 'Outline.11': class OutlineEntryObject +78 0 obj +<< /Dest [ 54 0 R + /XYZ + 62.69291 + 765.0236 + 0 ] + /Next 79 0 R + /Parent 66 0 R + /Prev 77 0 R + /Title (Caveats and limitations) >> +endobj +% 'Outline.12': class OutlineEntryObject +79 0 obj +<< /Dest [ 62 0 R + /XYZ + 62.69291 + 607.8236 + 0 ] + /Next 80 0 R + /Parent 66 0 R + /Prev 78 0 R + /Title (Compatibility notes) >> +endobj +% 'Outline.13': class OutlineEntryObject +80 0 obj +<< /Dest [ 62 0 R + /XYZ + 62.69291 + 232.8236 + 0 ] + /Parent 66 0 R + /Prev 79 0 R + /Title (LICENCE) >> +endobj +% 'R81': class PDFPages +81 0 obj +% page tree +<< /Count 15 + /Kids [ 37 0 R + 42 0 R + 43 0 R + 44 0 R + 45 0 R + 46 0 R + 47 0 R + 48 0 R + 49 0 R + 52 0 R + 53 0 R + 54 0 R + 56 0 R + 62 0 R + 63 0 R ] + /Type /Pages >> +endobj +% 'R82': class PDFStream +82 0 obj +% page stream +<< /Length 9103 >> +stream +1 0 0 1 0 0 cm BT /F1 12 Tf 14.4 TL ET +q +1 0 0 1 62.69291 741.0236 cm +q +BT 1 0 0 1 0 9.64 Tm 118.8249 0 Td 24 TL /F2 20 Tf 0 0 0 rg (The ) Tj /F3 20 Tf (decorator ) Tj /F2 20 Tf (module) Tj T* -118.8249 0 Td ET +Q +Q +q +1 0 0 1 62.69291 716.0236 cm +0 0 0 rg +BT /F4 10 Tf 12 TL ET +q +1 0 0 1 6 3 cm +q +0 0 0 rg +BT 1 0 0 1 0 4.82 Tm /F2 10 Tf 12 TL 36.93937 0 Td (Author:) Tj T* -36.93937 0 Td ET +Q +Q +q +1 0 0 1 91.03937 3 cm +q +0 0 0 rg +BT 1 0 0 1 0 4.82 Tm /F1 10 Tf 12 TL (Michele Simionato) Tj T* ET +Q +Q +q +Q +Q +q +1 0 0 1 62.69291 701.0236 cm +0 0 0 rg +BT /F4 10 Tf 12 TL ET +q +1 0 0 1 6 3 cm +q +0 0 0 rg +BT 1 0 0 1 0 4.82 Tm /F2 10 Tf 12 TL 39.69937 0 Td (E-mail:) Tj T* -39.69937 0 Td ET +Q +Q +q +1 0 0 1 91.03937 3 cm +q +0 0 .501961 rg +0 0 .501961 RG +BT 1 0 0 1 0 4.82 Tm /F1 10 Tf 12 TL (michele.simionato@gmail.com) Tj T* ET +Q +Q +q +Q +Q +q +1 0 0 1 62.69291 686.0236 cm +0 0 0 rg +BT /F4 10 Tf 12 TL ET +q +1 0 0 1 6 3 cm +q +0 0 0 rg +BT 1 0 0 1 0 4.82 Tm /F2 10 Tf 12 TL 33.02937 0 Td (Version:) Tj T* -33.02937 0 Td ET +Q +Q +q +1 0 0 1 91.03937 3 cm +q +0 0 0 rg +BT 1 0 0 1 0 4.82 Tm /F1 10 Tf 12 TL (3.2.0 \(2010-05-22\)) Tj T* ET +Q +Q +q +Q +Q +q +1 0 0 1 62.69291 671.0236 cm +0 0 0 rg +BT /F4 10 Tf 12 TL ET +q +1 0 0 1 6 3 cm +q +0 0 0 rg +BT 1 0 0 1 0 4.82 Tm /F2 10 Tf 12 TL 26.91937 0 Td (Requires:) Tj T* -26.91937 0 Td ET +Q +Q +q +1 0 0 1 91.03937 3 cm +q +0 0 0 rg +BT 1 0 0 1 0 4.82 Tm /F1 10 Tf 12 TL (Python 2.4+) Tj T* ET +Q +Q +q +Q +Q +q +1 0 0 1 62.69291 644.0236 cm +0 0 0 rg +BT /F4 10 Tf 12 TL ET +q +1 0 0 1 6 3 cm +q +0 0 0 rg +BT 1 0 0 1 0 16.82 Tm /F2 10 Tf 12 TL 25.25937 0 Td (Download) Tj T* 21.11 0 Td (page:) Tj T* -46.36937 0 Td ET +Q +Q +q +1 0 0 1 91.03937 15 cm +q +0 0 .501961 rg +0 0 .501961 RG +BT 1 0 0 1 0 4.82 Tm /F1 10 Tf 12 TL (http://pypi.python.org/pypi/decorator/3.2.0) Tj T* ET +Q +Q +q +Q +Q +q +1 0 0 1 62.69291 629.0236 cm +0 0 0 rg +BT /F4 10 Tf 12 TL ET +q +1 0 0 1 6 3 cm +q +0 0 0 rg +BT 1 0 0 1 0 4.82 Tm /F2 10 Tf 12 TL 16.91937 0 Td (Installation:) Tj T* -16.91937 0 Td ET +Q +Q +q +1 0 0 1 91.03937 3 cm +q +0 0 0 rg +BT 1 0 0 1 0 5.71 Tm /F5 10 Tf 12 TL (easy_install decorator) Tj T* ET +Q +Q +q +Q +Q +q +1 0 0 1 62.69291 614.0236 cm +0 0 0 rg +BT /F4 10 Tf 12 TL ET +q +1 0 0 1 6 3 cm +q +0 0 0 rg +BT 1 0 0 1 0 4.82 Tm /F2 10 Tf 12 TL 32.46937 0 Td (License:) Tj T* -32.46937 0 Td ET +Q +Q +q +1 0 0 1 91.03937 3 cm +q +0 0 0 rg +BT 1 0 0 1 0 4.82 Tm /F1 10 Tf 12 TL (BSD license) Tj T* ET +Q +Q +q +Q +Q +q +1 0 0 1 62.69291 581.0236 cm +q +BT 1 0 0 1 0 8.435 Tm 21 TL /F2 17.5 Tf 0 0 0 rg (Contents) Tj T* ET +Q +Q +q +1 0 0 1 62.69291 323.0236 cm +0 0 0 rg +BT /F4 10 Tf 12 TL ET +q +1 0 0 1 0 237 cm +q +BT 1 0 0 1 0 4.82 Tm 12 TL /F2 10 Tf 0 0 .501961 rg (Introduction) Tj T* ET +Q +Q +q +1 0 0 1 397.8898 237 cm +q +0 0 .501961 rg +0 0 .501961 RG +BT 1 0 0 1 0 4.82 Tm /F2 10 Tf 12 TL 66.44 0 Td (1) Tj T* -66.44 0 Td ET +Q +Q +q +1 0 0 1 0 219 cm +q +BT 1 0 0 1 0 4.82 Tm 12 TL /F2 10 Tf 0 0 .501961 rg (Definitions) Tj T* ET +Q +Q +q +1 0 0 1 397.8898 219 cm +q +0 0 .501961 rg +0 0 .501961 RG +BT 1 0 0 1 0 4.82 Tm /F2 10 Tf 12 TL 66.44 0 Td (2) Tj T* -66.44 0 Td ET +Q +Q +q +1 0 0 1 0 201 cm +q +BT 1 0 0 1 0 4.82 Tm 12 TL /F2 10 Tf 0 0 .501961 rg (Statement of the problem) Tj T* ET +Q +Q +q +1 0 0 1 397.8898 201 cm +q +0 0 .501961 rg +0 0 .501961 RG +BT 1 0 0 1 0 4.82 Tm /F2 10 Tf 12 TL 66.44 0 Td (2) Tj T* -66.44 0 Td ET +Q +Q +q +1 0 0 1 0 183 cm +q +BT 1 0 0 1 0 4.82 Tm 12 TL /F2 10 Tf 0 0 .501961 rg (The solution) Tj T* ET +Q +Q +q +1 0 0 1 397.8898 183 cm +q +0 0 .501961 rg +0 0 .501961 RG +BT 1 0 0 1 0 4.82 Tm /F2 10 Tf 12 TL 66.44 0 Td (3) Tj T* -66.44 0 Td ET +Q +Q +q +1 0 0 1 0 165 cm +q +BT 1 0 0 1 0 4.82 Tm 12 TL /F2 10 Tf 0 0 .501961 rg (A ) Tj /F3 10 Tf (trace ) Tj /F2 10 Tf (decorator) Tj T* ET +Q +Q +q +1 0 0 1 397.8898 165 cm +q +0 0 .501961 rg +0 0 .501961 RG +BT 1 0 0 1 0 4.82 Tm /F2 10 Tf 12 TL 66.44 0 Td (4) Tj T* -66.44 0 Td ET +Q +Q +q +1 0 0 1 0 147 cm +q +BT 1 0 0 1 0 4.82 Tm 12 TL /F3 10 Tf 0 0 .501961 rg (decorator ) Tj /F2 10 Tf (is a decorator) Tj T* ET +Q +Q +q +1 0 0 1 397.8898 147 cm +q +0 0 .501961 rg +0 0 .501961 RG +BT 1 0 0 1 0 4.82 Tm /F2 10 Tf 12 TL 66.44 0 Td (5) Tj T* -66.44 0 Td ET +Q +Q +q +1 0 0 1 0 129 cm +q +BT 1 0 0 1 0 4.82 Tm 12 TL /F3 10 Tf 0 0 .501961 rg (blocking) Tj T* ET +Q +Q +q +1 0 0 1 397.8898 129 cm +q +0 0 .501961 rg +0 0 .501961 RG +BT 1 0 0 1 0 4.82 Tm /F2 10 Tf 12 TL 66.44 0 Td (6) Tj T* -66.44 0 Td ET +Q +Q +q +1 0 0 1 0 111 cm +q +BT 1 0 0 1 0 4.82 Tm 12 TL /F3 10 Tf 0 0 .501961 rg (async) Tj T* ET +Q +Q +q +1 0 0 1 397.8898 111 cm +q +0 0 .501961 rg +0 0 .501961 RG +BT 1 0 0 1 0 4.82 Tm /F2 10 Tf 12 TL 66.44 0 Td (7) Tj T* -66.44 0 Td ET +Q +Q +q +1 0 0 1 0 93 cm +q +BT 1 0 0 1 0 4.82 Tm 12 TL /F2 10 Tf 0 0 .501961 rg (The ) Tj /F3 10 Tf (FunctionMaker ) Tj /F2 10 Tf (class) Tj T* ET +Q +Q +q +1 0 0 1 397.8898 93 cm +q +0 0 .501961 rg +0 0 .501961 RG +BT 1 0 0 1 0 4.82 Tm /F2 10 Tf 12 TL 66.44 0 Td (8) Tj T* -66.44 0 Td ET +Q +Q +q +1 0 0 1 0 75 cm +q +BT 1 0 0 1 0 4.82 Tm 12 TL /F2 10 Tf 0 0 .501961 rg (Getting the source code) Tj T* ET +Q +Q +q +1 0 0 1 397.8898 75 cm +q +0 0 .501961 rg +0 0 .501961 RG +BT 1 0 0 1 0 4.82 Tm /F2 10 Tf 12 TL 66.44 0 Td (9) Tj T* -66.44 0 Td ET +Q +Q +q +1 0 0 1 0 57 cm +q +BT 1 0 0 1 0 4.82 Tm 12 TL /F2 10 Tf 0 0 .501961 rg (Dealing with third party decorators) Tj T* ET +Q +Q +q +1 0 0 1 397.8898 57 cm +q +0 0 .501961 rg +0 0 .501961 RG +BT 1 0 0 1 0 4.82 Tm /F2 10 Tf 12 TL 60.88 0 Td (10) Tj T* -60.88 0 Td ET +Q +Q +q +1 0 0 1 0 39 cm +q +BT 1 0 0 1 0 4.82 Tm 12 TL /F2 10 Tf 0 0 .501961 rg (Caveats and limitations) Tj T* ET +Q +Q +q +1 0 0 1 397.8898 39 cm +q +0 0 .501961 rg +0 0 .501961 RG +BT 1 0 0 1 0 4.82 Tm /F2 10 Tf 12 TL 60.88 0 Td (12) Tj T* -60.88 0 Td ET +Q +Q +q +1 0 0 1 0 21 cm +q +BT 1 0 0 1 0 4.82 Tm 12 TL /F2 10 Tf 0 0 .501961 rg (Compatibility notes) Tj T* ET +Q +Q +q +1 0 0 1 397.8898 21 cm +q +0 0 .501961 rg +0 0 .501961 RG +BT 1 0 0 1 0 4.82 Tm /F2 10 Tf 12 TL 60.88 0 Td (14) Tj T* -60.88 0 Td ET +Q +Q +q +1 0 0 1 0 3 cm +q +BT 1 0 0 1 0 4.82 Tm 12 TL /F2 10 Tf 0 0 .501961 rg (LICENCE) Tj T* ET +Q +Q +q +1 0 0 1 397.8898 3 cm +q +0 0 .501961 rg +0 0 .501961 RG +BT 1 0 0 1 0 4.82 Tm /F2 10 Tf 12 TL 60.88 0 Td (14) Tj T* -60.88 0 Td ET +Q +Q +q +Q +Q +q +1 0 0 1 62.69291 290.0236 cm +q +BT 1 0 0 1 0 8.435 Tm 21 TL /F2 17.5 Tf 0 0 0 rg (Introduction) Tj T* ET +Q +Q +q +1 0 0 1 62.69291 224.0236 cm +q +0 0 0 rg +BT 1 0 0 1 0 52.82 Tm /F1 10 Tf 12 TL 3.995366 Tw (Python decorators are an interesting example of why syntactic sugar matters. In principle, their) Tj T* 0 Tw .151235 Tw (introduction in Python 2.4 changed nothing, since they do not provide any new functionality which was not) Tj T* 0 Tw 2.238555 Tw (already present in the language. In practice, their introduction has significantly changed the way we) Tj T* 0 Tw .098409 Tw (structure our programs in Python. I believe the change is for the best, and that decorators are a great idea) Tj T* 0 Tw (since:) Tj T* ET +Q +Q +q +1 0 0 1 62.69291 218.0236 cm +Q +q +1 0 0 1 62.69291 218.0236 cm +Q +q +1 0 0 1 62.69291 200.0236 cm +0 0 0 rg +BT /F4 10 Tf 12 TL ET +q +1 0 0 1 6 3 cm +q +0 0 0 rg +BT 1 0 0 1 0 4.82 Tm /F1 10 Tf 12 TL 10.5 0 Td (\177) Tj T* -10.5 0 Td ET +Q +Q +q +1 0 0 1 23 3 cm +q +0 0 0 rg +BT 1 0 0 1 0 4.82 Tm /F1 10 Tf 12 TL (decorators help reducing boilerplate code;) Tj T* ET +Q +Q +q +Q +Q +q +1 0 0 1 62.69291 200.0236 cm +Q +q +1 0 0 1 62.69291 200.0236 cm +Q +q +1 0 0 1 62.69291 182.0236 cm +0 0 0 rg +BT /F4 10 Tf 12 TL ET +q +1 0 0 1 6 3 cm +q +0 0 0 rg +BT 1 0 0 1 0 4.82 Tm /F1 10 Tf 12 TL 10.5 0 Td (\177) Tj T* -10.5 0 Td ET +Q +Q +q +1 0 0 1 23 3 cm +q +0 0 0 rg +BT 1 0 0 1 0 4.82 Tm /F1 10 Tf 12 TL (decorators help separation of concerns;) Tj T* ET +Q +Q +q +Q +Q +q +1 0 0 1 62.69291 182.0236 cm +Q +q +1 0 0 1 62.69291 182.0236 cm +Q +q +1 0 0 1 62.69291 164.0236 cm +0 0 0 rg +BT /F4 10 Tf 12 TL ET +q +1 0 0 1 6 3 cm +q +0 0 0 rg +BT 1 0 0 1 0 4.82 Tm /F1 10 Tf 12 TL 10.5 0 Td (\177) Tj T* -10.5 0 Td ET +Q +Q +q +1 0 0 1 23 3 cm +q +0 0 0 rg +BT 1 0 0 1 0 4.82 Tm /F1 10 Tf 12 TL (decorators enhance readability and maintenability;) Tj T* ET +Q +Q +q +Q +Q +q +1 0 0 1 62.69291 164.0236 cm +Q +q +1 0 0 1 62.69291 164.0236 cm +Q +q +1 0 0 1 62.69291 146.0236 cm +0 0 0 rg +BT /F4 10 Tf 12 TL ET +q +1 0 0 1 6 3 cm +q +0 0 0 rg +BT 1 0 0 1 0 4.82 Tm /F1 10 Tf 12 TL 10.5 0 Td (\177) Tj T* -10.5 0 Td ET +Q +Q +q +1 0 0 1 23 3 cm +q +0 0 0 rg +BT 1 0 0 1 0 4.82 Tm /F1 10 Tf 12 TL (decorators are explicit.) Tj T* ET +Q +Q +q +Q +Q +q +1 0 0 1 62.69291 146.0236 cm +Q +q +1 0 0 1 62.69291 146.0236 cm +Q +q +1 0 0 1 62.69291 104.0236 cm +q +0 0 0 rg +BT 1 0 0 1 0 28.82 Tm /F1 10 Tf 12 TL .848876 Tw (Still, as of now, writing custom decorators correctly requires some experience and it is not as easy as it) Tj T* 0 Tw 1.049269 Tw (could be. For instance, typical implementations of decorators involve nested functions, and we all know) Tj T* 0 Tw (that flat is better than nested.) Tj T* ET +Q +Q + +endstream + +endobj +% 'R83': class PDFStream +83 0 obj +% page stream +<< /Length 7636 >> +stream +1 0 0 1 0 0 cm BT /F1 12 Tf 14.4 TL ET +q +1 0 0 1 62.69291 717.0236 cm +q +BT 1 0 0 1 0 40.82 Tm 1.093735 Tw 12 TL /F1 10 Tf 0 0 0 rg (The aim of the ) Tj /F5 10 Tf (decorator ) Tj /F1 10 Tf (module it to simplify the usage of decorators for the average programmer,) Tj T* 0 Tw 2.456136 Tw (and to popularize decorators by showing various non-trivial examples. Of course, as all techniques,) Tj T* 0 Tw 2.234987 Tw (decorators can be abused \(I have seen that\) and you should not try to solve every problem with a) Tj T* 0 Tw (decorator, just because you can.) Tj T* ET +Q +Q +q +1 0 0 1 62.69291 687.0236 cm +q +BT 1 0 0 1 0 16.82 Tm .13561 Tw 12 TL /F1 10 Tf 0 0 0 rg (You may find the source code for all the examples discussed here in the ) Tj /F5 10 Tf (documentation.py ) Tj /F1 10 Tf (file, which) Tj T* 0 Tw (contains this documentation in the form of doctests.) Tj T* ET +Q +Q +q +1 0 0 1 62.69291 654.0236 cm +q +BT 1 0 0 1 0 8.435 Tm 21 TL /F2 17.5 Tf 0 0 0 rg (Definitions) Tj T* ET +Q +Q +q +1 0 0 1 62.69291 612.0236 cm +q +0 0 0 rg +BT 1 0 0 1 0 28.82 Tm /F1 10 Tf 12 TL 2.37561 Tw (Technically speaking, any Python object which can be called with one argument can be used as a) Tj T* 0 Tw .472339 Tw (decorator. However, this definition is somewhat too large to be really useful. It is more convenient to split) Tj T* 0 Tw (the generic class of decorators in two subclasses:) Tj T* ET +Q +Q +q +1 0 0 1 62.69291 606.0236 cm +Q +q +1 0 0 1 62.69291 606.0236 cm +Q +q +1 0 0 1 62.69291 576.0236 cm +0 0 0 rg +BT /F4 10 Tf 12 TL ET +q +1 0 0 1 6 15 cm +q +0 0 0 rg +BT 1 0 0 1 0 4.82 Tm /F1 10 Tf 12 TL 10.5 0 Td (\177) Tj T* -10.5 0 Td ET +Q +Q +q +1 0 0 1 23 3 cm +q +BT 1 0 0 1 0 16.82 Tm 2.68748 Tw 12 TL /F6 10 Tf 0 0 0 rg (signature-preserving ) Tj /F1 10 Tf (decorators, i.e. callable objects taking a function as input and returning a) Tj T* 0 Tw (function ) Tj /F6 10 Tf (with the same signature ) Tj /F1 10 Tf (as output;) Tj T* ET +Q +Q +q +Q +Q +q +1 0 0 1 62.69291 576.0236 cm +Q +q +1 0 0 1 62.69291 576.0236 cm +Q +q +1 0 0 1 62.69291 546.0236 cm +0 0 0 rg +BT /F4 10 Tf 12 TL ET +q +1 0 0 1 6 15 cm +q +0 0 0 rg +BT 1 0 0 1 0 4.82 Tm /F1 10 Tf 12 TL 10.5 0 Td (\177) Tj T* -10.5 0 Td ET +Q +Q +q +1 0 0 1 23 3 cm +q +BT 1 0 0 1 0 16.82 Tm 1.43498 Tw 12 TL /F6 10 Tf 0 0 0 rg (signature-changing ) Tj /F1 10 Tf (decorators, i.e. decorators that change the signature of their input function, or) Tj T* 0 Tw (decorators returning non-callable objects.) Tj T* ET +Q +Q +q +Q +Q +q +1 0 0 1 62.69291 546.0236 cm +Q +q +1 0 0 1 62.69291 546.0236 cm +Q +q +1 0 0 1 62.69291 504.0236 cm +q +BT 1 0 0 1 0 28.82 Tm 2.832706 Tw 12 TL /F1 10 Tf 0 0 0 rg (Signature-changing decorators have their use: for instance the builtin classes ) Tj /F5 10 Tf (staticmethod ) Tj /F1 10 Tf (and) Tj T* 0 Tw 1.506651 Tw /F5 10 Tf (classmethod ) Tj /F1 10 Tf (are in this group, since they take functions and return descriptor objects which are not) Tj T* 0 Tw (functions, nor callables.) Tj T* ET +Q +Q +q +1 0 0 1 62.69291 474.0236 cm +q +0 0 0 rg +BT 1 0 0 1 0 16.82 Tm /F1 10 Tf 12 TL 1.735814 Tw (However, signature-preserving decorators are more common and easier to reason about; in particular) Tj T* 0 Tw (signature-preserving decorators can be composed together whereas other decorators in general cannot.) Tj T* ET +Q +Q +q +1 0 0 1 62.69291 444.0236 cm +q +0 0 0 rg +BT 1 0 0 1 0 16.82 Tm /F1 10 Tf 12 TL .494983 Tw (Writing signature-preserving decorators from scratch is not that obvious, especially if one wants to define) Tj T* 0 Tw (proper decorators that can accept functions with any signature. A simple example will clarify the issue.) Tj T* ET +Q +Q +q +1 0 0 1 62.69291 411.0236 cm +q +BT 1 0 0 1 0 8.435 Tm 21 TL /F2 17.5 Tf 0 0 0 rg (Statement of the problem) Tj T* ET +Q +Q +q +1 0 0 1 62.69291 333.0236 cm +q +BT 1 0 0 1 0 64.82 Tm .351235 Tw 12 TL /F1 10 Tf 0 0 0 rg (A very common use case for decorators is the memoization of functions. A ) Tj /F5 10 Tf (memoize ) Tj /F1 10 Tf (decorator works by) Tj T* 0 Tw .871988 Tw (caching the result of the function call in a dictionary, so that the next time the function is called with the) Tj T* 0 Tw 2.350651 Tw (same input parameters the result is retrieved from the cache and not recomputed. There are many) Tj T* 0 Tw 2.92247 Tw (implementations of ) Tj /F5 10 Tf (memoize ) Tj /F1 10 Tf (in ) Tj 0 0 .501961 rg (http://www.python.org/moin/PythonDecoratorLibrary) Tj 0 0 0 rg (, but they do not) Tj T* 0 Tw 2.683984 Tw (preserve the signature. A simple implementation could be the following \(notice that in general it is) Tj T* 0 Tw (impossible to memoize correctly something that depends on non-hashable arguments\):) Tj T* ET +Q +Q +q +1 0 0 1 62.69291 143.8236 cm +q +q +1 0 0 1 0 0 cm +q +1 0 0 1 6.6 6.6 cm +q +.662745 .662745 .662745 RG +.5 w +.960784 .960784 .862745 rg +n -6 -6 468.6898 180 re B* +Q +q +BT 1 0 0 1 0 161.71 Tm 12 TL /F3 10 Tf 0 .501961 0 rg (def) Tj /F5 10 Tf 0 0 0 rg ( ) Tj 0 0 1 rg (memoize_uw) Tj 0 0 0 rg (\() Tj (func) Tj (\):) Tj T* ( ) Tj (func) Tj .4 .4 .4 rg (.) Tj 0 0 0 rg (cache) Tj ( ) Tj .4 .4 .4 rg (=) Tj 0 0 0 rg ( ) Tj ({}) Tj T* ( ) Tj /F3 10 Tf 0 .501961 0 rg (def) Tj /F5 10 Tf 0 0 0 rg ( ) Tj 0 0 1 rg (memoize) Tj 0 0 0 rg (\() Tj .4 .4 .4 rg (*) Tj 0 0 0 rg (args) Tj (,) Tj ( ) Tj .4 .4 .4 rg (**) Tj 0 0 0 rg (kw) Tj (\):) Tj T* ( ) Tj /F3 10 Tf 0 .501961 0 rg (if) Tj /F5 10 Tf 0 0 0 rg ( ) Tj (kw) Tj (:) Tj ( ) Tj /F7 10 Tf .25098 .501961 .501961 rg (# frozenset is used to ensure hashability) Tj /F5 10 Tf 0 0 0 rg T* ( ) Tj (key) Tj ( ) Tj .4 .4 .4 rg (=) Tj 0 0 0 rg ( ) Tj (args) Tj (,) Tj ( ) Tj (frozenset) Tj (\() Tj (kw) Tj .4 .4 .4 rg (.) Tj 0 0 0 rg (iteritems) Tj (\(\)\)) Tj T* ( ) Tj /F3 10 Tf 0 .501961 0 rg (else) Tj /F5 10 Tf 0 0 0 rg (:) Tj T* ( ) Tj (key) Tj ( ) Tj .4 .4 .4 rg (=) Tj 0 0 0 rg ( ) Tj (args) Tj T* ( ) Tj (cache) Tj ( ) Tj .4 .4 .4 rg (=) Tj 0 0 0 rg ( ) Tj (func) Tj .4 .4 .4 rg (.) Tj 0 0 0 rg (cache) Tj T* ( ) Tj /F3 10 Tf 0 .501961 0 rg (if) Tj /F5 10 Tf 0 0 0 rg ( ) Tj (key) Tj ( ) Tj /F3 10 Tf .666667 .133333 1 rg (in) Tj /F5 10 Tf 0 0 0 rg ( ) Tj (cache) Tj (:) Tj T* ( ) Tj /F3 10 Tf 0 .501961 0 rg (return) Tj /F5 10 Tf 0 0 0 rg ( ) Tj (cache) Tj ([) Tj (key) Tj (]) Tj T* ( ) Tj /F3 10 Tf 0 .501961 0 rg (else) Tj /F5 10 Tf 0 0 0 rg (:) Tj T* ( ) Tj (cache) Tj ([) Tj (key) Tj (]) Tj ( ) Tj .4 .4 .4 rg (=) Tj 0 0 0 rg ( ) Tj (result) Tj ( ) Tj .4 .4 .4 rg (=) Tj 0 0 0 rg ( ) Tj (func) Tj (\() Tj .4 .4 .4 rg (*) Tj 0 0 0 rg (args) Tj (,) Tj ( ) Tj .4 .4 .4 rg (**) Tj 0 0 0 rg (kw) Tj (\)) Tj T* ( ) Tj /F3 10 Tf 0 .501961 0 rg (return) Tj /F5 10 Tf 0 0 0 rg ( ) Tj (result) Tj T* ( ) Tj /F3 10 Tf 0 .501961 0 rg (return) Tj /F5 10 Tf 0 0 0 rg ( ) Tj (functools) Tj .4 .4 .4 rg (.) Tj 0 0 0 rg (update_wrapper) Tj (\() Tj (memoize) Tj (,) Tj ( ) Tj (func) Tj (\)) Tj T* ET +Q +Q +Q +Q +Q +q +1 0 0 1 62.69291 87.82362 cm +q +BT 1 0 0 1 0 40.82 Tm 1.801412 Tw 12 TL /F1 10 Tf 0 0 0 rg (Here we used the ) Tj 0 0 .501961 rg (functools.update_wrapper ) Tj 0 0 0 rg (utility, which has been added in Python 2.5 expressly to) Tj T* 0 Tw .91686 Tw (simplify the definition of decorators \(in older versions of Python you need to copy the function attributes) Tj T* 0 Tw .580814 Tw /F5 10 Tf (__name__) Tj /F1 10 Tf (, ) Tj /F5 10 Tf (__doc__) Tj /F1 10 Tf (, ) Tj /F5 10 Tf (__module__ ) Tj /F1 10 Tf (and ) Tj /F5 10 Tf (__dict__ ) Tj /F1 10 Tf (from the original function to the decorated function) Tj T* 0 Tw (by hand\).) Tj T* ET +Q +Q + +endstream + +endobj +% 'R84': class PDFStream +84 0 obj +% page stream +<< /Length 8051 >> +stream +1 0 0 1 0 0 cm BT /F1 12 Tf 14.4 TL ET +q +1 0 0 1 62.69291 729.0236 cm +q +BT 1 0 0 1 0 28.82 Tm 2.517126 Tw 12 TL /F1 10 Tf 0 0 0 rg (The implementation above works in the sense that the decorator can accept functions with generic) Tj T* 0 Tw 1.233615 Tw (signatures; unfortunately this implementation does ) Tj /F6 10 Tf (not ) Tj /F1 10 Tf (define a signature-preserving decorator, since in) Tj T* 0 Tw (general ) Tj /F5 10 Tf (memoize_uw ) Tj /F1 10 Tf (returns a function with a ) Tj /F6 10 Tf (different signature ) Tj /F1 10 Tf (from the original function.) Tj T* ET +Q +Q +q +1 0 0 1 62.69291 711.0236 cm +q +0 0 0 rg +BT 1 0 0 1 0 4.82 Tm /F1 10 Tf 12 TL (Consider for instance the following case:) Tj T* ET +Q +Q +q +1 0 0 1 62.69291 641.8236 cm +q +q +1 0 0 1 0 0 cm +q +1 0 0 1 6.6 6.6 cm +q +.662745 .662745 .662745 RG +.5 w +.960784 .960784 .862745 rg +n -6 -6 468.6898 60 re B* +Q +q +BT 1 0 0 1 0 41.71 Tm 12 TL /F5 10 Tf .4 .4 .4 rg (>) Tj (>) Tj (>) Tj 0 0 0 rg ( ) Tj .666667 .133333 1 rg (@memoize_uw) Tj 0 0 0 rg T* .4 .4 .4 rg (...) Tj 0 0 0 rg ( ) Tj /F3 10 Tf 0 .501961 0 rg (def) Tj /F5 10 Tf 0 0 0 rg ( ) Tj 0 0 1 rg (f1) Tj 0 0 0 rg (\() Tj (x) Tj (\):) Tj T* .4 .4 .4 rg (...) Tj 0 0 0 rg ( ) Tj (time) Tj .4 .4 .4 rg (.) Tj 0 0 0 rg (sleep) Tj (\() Tj .4 .4 .4 rg (1) Tj 0 0 0 rg (\)) Tj ( ) Tj /F7 10 Tf .25098 .501961 .501961 rg (# simulate some long computation) Tj /F5 10 Tf 0 0 0 rg T* .4 .4 .4 rg (...) Tj 0 0 0 rg ( ) Tj /F3 10 Tf 0 .501961 0 rg (return) Tj /F5 10 Tf 0 0 0 rg ( ) Tj (x) Tj T* ET +Q +Q +Q +Q +Q +q +1 0 0 1 62.69291 609.8236 cm +q +BT 1 0 0 1 0 16.82 Tm .26311 Tw 12 TL /F1 10 Tf 0 0 0 rg (Here the original function takes a single argument named ) Tj /F5 10 Tf (x) Tj /F1 10 Tf (, but the decorated function takes any number) Tj T* 0 Tw (of arguments and keyword arguments:) Tj T* ET +Q +Q +q +1 0 0 1 62.69291 552.6236 cm +q +q +1 0 0 1 0 0 cm +q +1 0 0 1 6.6 6.6 cm +q +.662745 .662745 .662745 RG +.5 w +.960784 .960784 .862745 rg +n -6 -6 468.6898 48 re B* +Q +q +BT 1 0 0 1 0 29.71 Tm 12 TL /F5 10 Tf .4 .4 .4 rg (>) Tj (>) Tj (>) Tj 0 0 0 rg ( ) Tj /F3 10 Tf 0 .501961 0 rg (from) Tj /F5 10 Tf 0 0 0 rg ( ) Tj /F3 10 Tf 0 0 1 rg (inspect) Tj /F5 10 Tf 0 0 0 rg ( ) Tj /F3 10 Tf 0 .501961 0 rg (import) Tj /F5 10 Tf 0 0 0 rg ( ) Tj (getargspec) Tj T* .4 .4 .4 rg (>) Tj (>) Tj (>) Tj 0 0 0 rg ( ) Tj /F3 10 Tf 0 .501961 0 rg (print) Tj /F5 10 Tf 0 0 0 rg ( ) Tj (getargspec) Tj (\() Tj (f1) Tj (\)) Tj ( ) Tj /F7 10 Tf .25098 .501961 .501961 rg (# I am using Python 2.6+ here) Tj /F5 10 Tf 0 0 0 rg T* (ArgSpec) Tj (\() Tj (args) Tj .4 .4 .4 rg (=) Tj 0 0 0 rg ([],) Tj ( ) Tj (varargs) Tj .4 .4 .4 rg (=) Tj .729412 .129412 .129412 rg ('args') Tj 0 0 0 rg (,) Tj ( ) Tj (keywords) Tj .4 .4 .4 rg (=) Tj .729412 .129412 .129412 rg ('kw') Tj 0 0 0 rg (,) Tj ( ) Tj (defaults) Tj .4 .4 .4 rg (=) Tj 0 .501961 0 rg (None) Tj 0 0 0 rg (\)) Tj T* ET +Q +Q +Q +Q +Q +q +1 0 0 1 62.69291 508.6236 cm +q +BT 1 0 0 1 0 28.82 Tm .411235 Tw 12 TL /F1 10 Tf 0 0 0 rg (This means that introspection tools such as pydoc will give wrong informations about the signature of ) Tj /F5 10 Tf (f1) Tj /F1 10 Tf (.) Tj T* 0 Tw .161654 Tw (This is pretty bad: pydoc will tell you that the function accepts a generic signature ) Tj /F5 10 Tf (*args) Tj /F1 10 Tf (, ) Tj /F5 10 Tf (**kw) Tj /F1 10 Tf (, but when) Tj T* 0 Tw (you try to call the function with more than an argument, you will get an error:) Tj T* ET +Q +Q +q +1 0 0 1 62.69291 439.4236 cm +q +q +1 0 0 1 0 0 cm +q +1 0 0 1 6.6 6.6 cm +q +.662745 .662745 .662745 RG +.5 w +.960784 .960784 .862745 rg +n -6 -6 468.6898 60 re B* +Q +q +BT 1 0 0 1 0 41.71 Tm 12 TL /F5 10 Tf .4 .4 .4 rg (>) Tj (>) Tj (>) Tj 0 0 0 rg ( ) Tj (f1) Tj (\() Tj .4 .4 .4 rg (0) Tj 0 0 0 rg (,) Tj ( ) Tj .4 .4 .4 rg (1) Tj 0 0 0 rg (\)) Tj T* (Traceback) Tj ( ) Tj (\() Tj (most) Tj ( ) Tj (recent) Tj ( ) Tj (call) Tj ( ) Tj (last) Tj (\):) Tj T* ( ) Tj .4 .4 .4 rg (...) Tj 0 0 0 rg T* /F3 10 Tf .823529 .254902 .227451 rg (TypeError) Tj /F5 10 Tf 0 0 0 rg (:) Tj ( ) Tj (f1) Tj (\(\)) Tj ( ) Tj (takes) Tj ( ) Tj (exactly) Tj ( ) Tj .4 .4 .4 rg (1) Tj 0 0 0 rg ( ) Tj (argument) Tj ( ) Tj (\() Tj .4 .4 .4 rg (2) Tj 0 0 0 rg ( ) Tj (given) Tj (\)) Tj T* ET +Q +Q +Q +Q +Q +q +1 0 0 1 62.69291 406.4236 cm +q +BT 1 0 0 1 0 8.435 Tm 21 TL /F2 17.5 Tf 0 0 0 rg (The solution) Tj T* ET +Q +Q +q +1 0 0 1 62.69291 364.4236 cm +q +BT 1 0 0 1 0 28.82 Tm 3.313984 Tw 12 TL /F1 10 Tf 0 0 0 rg (The solution is to provide a generic factory of generators, which hides the complexity of making) Tj T* 0 Tw 3.362976 Tw (signature-preserving decorators from the application programmer. The ) Tj /F5 10 Tf (decorator ) Tj /F1 10 Tf (function in the) Tj T* 0 Tw /F5 10 Tf (decorator ) Tj /F1 10 Tf (module is such a factory:) Tj T* ET +Q +Q +q +1 0 0 1 62.69291 331.2236 cm +q +q +1 0 0 1 0 0 cm +q +1 0 0 1 6.6 6.6 cm +q +.662745 .662745 .662745 RG +.5 w +.960784 .960784 .862745 rg +n -6 -6 468.6898 24 re B* +Q +q +BT 1 0 0 1 0 5.71 Tm 12 TL /F5 10 Tf .4 .4 .4 rg (>) Tj (>) Tj (>) Tj 0 0 0 rg ( ) Tj /F3 10 Tf 0 .501961 0 rg (from) Tj /F5 10 Tf 0 0 0 rg ( ) Tj /F3 10 Tf 0 0 1 rg (decorator) Tj /F5 10 Tf 0 0 0 rg ( ) Tj /F3 10 Tf 0 .501961 0 rg (import) Tj /F5 10 Tf 0 0 0 rg ( ) Tj (decorator) Tj T* ET +Q +Q +Q +Q +Q +q +1 0 0 1 62.69291 275.2236 cm +q +BT 1 0 0 1 0 40.82 Tm 1.716412 Tw 12 TL /F5 10 Tf 0 0 0 rg (decorator ) Tj /F1 10 Tf (takes two arguments, a caller function describing the functionality of the decorator and a) Tj T* 0 Tw .821984 Tw (function to be decorated; it returns the decorated function. The caller function must have signature ) Tj /F5 10 Tf (\(f,) Tj T* 0 Tw .65061 Tw (*args, **kw\) ) Tj /F1 10 Tf (and it must call the original function ) Tj /F5 10 Tf (f ) Tj /F1 10 Tf (with arguments ) Tj /F5 10 Tf (args ) Tj /F1 10 Tf (and ) Tj /F5 10 Tf (kw) Tj /F1 10 Tf (, implementing the) Tj T* 0 Tw (wanted capability, i.e. memoization in this case:) Tj T* ET +Q +Q +q +1 0 0 1 62.69291 122.0236 cm +q +q +1 0 0 1 0 0 cm +q +1 0 0 1 6.6 6.6 cm +q +.662745 .662745 .662745 RG +.5 w +.960784 .960784 .862745 rg +n -6 -6 468.6898 144 re B* +Q +q +BT 1 0 0 1 0 125.71 Tm 12 TL /F3 10 Tf 0 .501961 0 rg (def) Tj /F5 10 Tf 0 0 0 rg ( ) Tj 0 0 1 rg (_memoize) Tj 0 0 0 rg (\() Tj (func) Tj (,) Tj ( ) Tj .4 .4 .4 rg (*) Tj 0 0 0 rg (args) Tj (,) Tj ( ) Tj .4 .4 .4 rg (**) Tj 0 0 0 rg (kw) Tj (\):) Tj T* ( ) Tj /F3 10 Tf 0 .501961 0 rg (if) Tj /F5 10 Tf 0 0 0 rg ( ) Tj (kw) Tj (:) Tj ( ) Tj /F7 10 Tf .25098 .501961 .501961 rg (# frozenset is used to ensure hashability) Tj /F5 10 Tf 0 0 0 rg T* ( ) Tj (key) Tj ( ) Tj .4 .4 .4 rg (=) Tj 0 0 0 rg ( ) Tj (args) Tj (,) Tj ( ) Tj (frozenset) Tj (\() Tj (kw) Tj .4 .4 .4 rg (.) Tj 0 0 0 rg (iteritems) Tj (\(\)\)) Tj T* ( ) Tj /F3 10 Tf 0 .501961 0 rg (else) Tj /F5 10 Tf 0 0 0 rg (:) Tj T* ( ) Tj (key) Tj ( ) Tj .4 .4 .4 rg (=) Tj 0 0 0 rg ( ) Tj (args) Tj T* ( ) Tj (cache) Tj ( ) Tj .4 .4 .4 rg (=) Tj 0 0 0 rg ( ) Tj (func) Tj .4 .4 .4 rg (.) Tj 0 0 0 rg (cache) Tj ( ) Tj /F7 10 Tf .25098 .501961 .501961 rg (# attributed added by memoize) Tj /F5 10 Tf 0 0 0 rg T* ( ) Tj /F3 10 Tf 0 .501961 0 rg (if) Tj /F5 10 Tf 0 0 0 rg ( ) Tj (key) Tj ( ) Tj /F3 10 Tf .666667 .133333 1 rg (in) Tj /F5 10 Tf 0 0 0 rg ( ) Tj (cache) Tj (:) Tj T* ( ) Tj /F3 10 Tf 0 .501961 0 rg (return) Tj /F5 10 Tf 0 0 0 rg ( ) Tj (cache) Tj ([) Tj (key) Tj (]) Tj T* ( ) Tj /F3 10 Tf 0 .501961 0 rg (else) Tj /F5 10 Tf 0 0 0 rg (:) Tj T* ( ) Tj (cache) Tj ([) Tj (key) Tj (]) Tj ( ) Tj .4 .4 .4 rg (=) Tj 0 0 0 rg ( ) Tj (result) Tj ( ) Tj .4 .4 .4 rg (=) Tj 0 0 0 rg ( ) Tj (func) Tj (\() Tj .4 .4 .4 rg (*) Tj 0 0 0 rg (args) Tj (,) Tj ( ) Tj .4 .4 .4 rg (**) Tj 0 0 0 rg (kw) Tj (\)) Tj T* ( ) Tj /F3 10 Tf 0 .501961 0 rg (return) Tj /F5 10 Tf 0 0 0 rg ( ) Tj (result) Tj T* ET +Q +Q +Q +Q +Q +q +1 0 0 1 62.69291 102.0236 cm +q +0 0 0 rg +BT 1 0 0 1 0 4.82 Tm /F1 10 Tf 12 TL (At this point you can define your decorator as follows:) Tj T* ET +Q +Q + +endstream + +endobj +% 'R85': class PDFStream +85 0 obj +% page stream +<< /Length 7158 >> +stream +1 0 0 1 0 0 cm BT /F1 12 Tf 14.4 TL ET +q +1 0 0 1 62.69291 715.8236 cm +q +q +1 0 0 1 0 0 cm +q +1 0 0 1 6.6 6.6 cm +q +.662745 .662745 .662745 RG +.5 w +.960784 .960784 .862745 rg +n -6 -6 468.6898 48 re B* +Q +q +BT 1 0 0 1 0 29.71 Tm 12 TL /F3 10 Tf 0 .501961 0 rg (def) Tj /F5 10 Tf 0 0 0 rg ( ) Tj 0 0 1 rg (memoize) Tj 0 0 0 rg (\() Tj (f) Tj (\):) Tj T* ( ) Tj (f) Tj .4 .4 .4 rg (.) Tj 0 0 0 rg (cache) Tj ( ) Tj .4 .4 .4 rg (=) Tj 0 0 0 rg ( ) Tj ({}) Tj T* ( ) Tj /F3 10 Tf 0 .501961 0 rg (return) Tj /F5 10 Tf 0 0 0 rg ( ) Tj (decorator) Tj (\() Tj (_memoize) Tj (,) Tj ( ) Tj (f) Tj (\)) Tj T* ET +Q +Q +Q +Q +Q +q +1 0 0 1 62.69291 671.8236 cm +q +BT 1 0 0 1 0 28.82 Tm .12561 Tw 12 TL /F1 10 Tf 0 0 0 rg (The difference with respect to the ) Tj /F5 10 Tf (memoize_uw ) Tj /F1 10 Tf (approach, which is based on nested functions, is that the) Tj T* 0 Tw 2.59528 Tw (decorator module forces you to lift the inner function at the outer level \() Tj /F6 10 Tf (flat is better than nested) Tj /F1 10 Tf (\).) Tj T* 0 Tw (Moreover, you are forced to pass explicitly the function you want to decorate to the caller function.) Tj T* ET +Q +Q +q +1 0 0 1 62.69291 653.8236 cm +q +0 0 0 rg +BT 1 0 0 1 0 4.82 Tm /F1 10 Tf 12 TL (Here is a test of usage:) Tj T* ET +Q +Q +q +1 0 0 1 62.69291 512.6236 cm +q +q +1 0 0 1 0 0 cm +q +1 0 0 1 6.6 6.6 cm +q +.662745 .662745 .662745 RG +.5 w +.960784 .960784 .862745 rg +n -6 -6 468.6898 132 re B* +Q +q +BT 1 0 0 1 0 113.71 Tm 12 TL /F5 10 Tf .4 .4 .4 rg (>) Tj (>) Tj (>) Tj 0 0 0 rg ( ) Tj .666667 .133333 1 rg (@memoize) Tj 0 0 0 rg T* .4 .4 .4 rg (...) Tj 0 0 0 rg ( ) Tj /F3 10 Tf 0 .501961 0 rg (def) Tj /F5 10 Tf 0 0 0 rg ( ) Tj 0 0 1 rg (heavy_computation) Tj 0 0 0 rg (\(\):) Tj T* .4 .4 .4 rg (...) Tj 0 0 0 rg ( ) Tj (time) Tj .4 .4 .4 rg (.) Tj 0 0 0 rg (sleep) Tj (\() Tj .4 .4 .4 rg (2) Tj 0 0 0 rg (\)) Tj T* .4 .4 .4 rg (...) Tj 0 0 0 rg ( ) Tj /F3 10 Tf 0 .501961 0 rg (return) Tj /F5 10 Tf 0 0 0 rg ( ) Tj .729412 .129412 .129412 rg ("done") Tj 0 0 0 rg T* T* .4 .4 .4 rg (>) Tj (>) Tj (>) Tj 0 0 0 rg ( ) Tj /F3 10 Tf 0 .501961 0 rg (print) Tj /F5 10 Tf 0 0 0 rg ( ) Tj (heavy_computation) Tj (\(\)) Tj ( ) Tj /F7 10 Tf .25098 .501961 .501961 rg (# the first time it will take 2 seconds) Tj /F5 10 Tf 0 0 0 rg T* (done) Tj T* T* .4 .4 .4 rg (>) Tj (>) Tj (>) Tj 0 0 0 rg ( ) Tj /F3 10 Tf 0 .501961 0 rg (print) Tj /F5 10 Tf 0 0 0 rg ( ) Tj (heavy_computation) Tj (\(\)) Tj ( ) Tj /F7 10 Tf .25098 .501961 .501961 rg (# the second time it will be instantaneous) Tj /F5 10 Tf 0 0 0 rg T* (done) Tj T* ET +Q +Q +Q +Q +Q +q +1 0 0 1 62.69291 492.6236 cm +q +BT 1 0 0 1 0 4.82 Tm 12 TL /F1 10 Tf 0 0 0 rg (The signature of ) Tj /F5 10 Tf (heavy_computation ) Tj /F1 10 Tf (is the one you would expect:) Tj T* ET +Q +Q +q +1 0 0 1 62.69291 447.4236 cm +q +q +1 0 0 1 0 0 cm +q +1 0 0 1 6.6 6.6 cm +q +.662745 .662745 .662745 RG +.5 w +.960784 .960784 .862745 rg +n -6 -6 468.6898 36 re B* +Q +q +BT 1 0 0 1 0 17.71 Tm 12 TL /F5 10 Tf .4 .4 .4 rg (>) Tj (>) Tj (>) Tj 0 0 0 rg ( ) Tj /F3 10 Tf 0 .501961 0 rg (print) Tj /F5 10 Tf 0 0 0 rg ( ) Tj (getargspec) Tj (\() Tj (heavy_computation) Tj (\)) Tj T* (ArgSpec) Tj (\() Tj (args) Tj .4 .4 .4 rg (=) Tj 0 0 0 rg ([],) Tj ( ) Tj (varargs) Tj .4 .4 .4 rg (=) Tj 0 .501961 0 rg (None) Tj 0 0 0 rg (,) Tj ( ) Tj (keywords) Tj .4 .4 .4 rg (=) Tj 0 .501961 0 rg (None) Tj 0 0 0 rg (,) Tj ( ) Tj (defaults) Tj .4 .4 .4 rg (=) Tj 0 .501961 0 rg (None) Tj 0 0 0 rg (\)) Tj T* ET +Q +Q +Q +Q +Q +q +1 0 0 1 62.69291 414.4236 cm +q +BT 1 0 0 1 0 8.435 Tm 21 TL /F2 17.5 Tf 0 0 0 rg (A ) Tj /F3 17.5 Tf (trace ) Tj /F2 17.5 Tf (decorator) Tj T* ET +Q +Q +q +1 0 0 1 62.69291 384.4236 cm +q +BT 1 0 0 1 0 16.82 Tm .479398 Tw 12 TL /F1 10 Tf 0 0 0 rg (As an additional example, here is how you can define a trivial ) Tj /F5 10 Tf (trace ) Tj /F1 10 Tf (decorator, which prints a message) Tj T* 0 Tw (everytime the traced function is called:) Tj T* ET +Q +Q +q +1 0 0 1 62.69291 327.2236 cm +q +q +1 0 0 1 0 0 cm +q +1 0 0 1 6.6 6.6 cm +q +.662745 .662745 .662745 RG +.5 w +.960784 .960784 .862745 rg +n -6 -6 468.6898 48 re B* +Q +q +BT 1 0 0 1 0 29.71 Tm 12 TL /F3 10 Tf 0 .501961 0 rg (def) Tj /F5 10 Tf 0 0 0 rg ( ) Tj 0 0 1 rg (_trace) Tj 0 0 0 rg (\() Tj (f) Tj (,) Tj ( ) Tj .4 .4 .4 rg (*) Tj 0 0 0 rg (args) Tj (,) Tj ( ) Tj .4 .4 .4 rg (**) Tj 0 0 0 rg (kw) Tj (\):) Tj T* ( ) Tj /F3 10 Tf 0 .501961 0 rg (print) Tj /F5 10 Tf 0 0 0 rg ( ) Tj .729412 .129412 .129412 rg ("calling ) Tj /F3 10 Tf .733333 .4 .533333 rg (%s) Tj /F5 10 Tf .729412 .129412 .129412 rg ( with args ) Tj /F3 10 Tf .733333 .4 .533333 rg (%s) Tj /F5 10 Tf .729412 .129412 .129412 rg (, ) Tj /F3 10 Tf .733333 .4 .533333 rg (%s) Tj /F5 10 Tf .729412 .129412 .129412 rg (") Tj 0 0 0 rg ( ) Tj .4 .4 .4 rg (%) Tj 0 0 0 rg ( ) Tj (\() Tj (f) Tj .4 .4 .4 rg (.) Tj 0 0 0 rg (__name__) Tj (,) Tj ( ) Tj (args) Tj (,) Tj ( ) Tj (kw) Tj (\)) Tj T* ( ) Tj /F3 10 Tf 0 .501961 0 rg (return) Tj /F5 10 Tf 0 0 0 rg ( ) Tj (f) Tj (\() Tj .4 .4 .4 rg (*) Tj 0 0 0 rg (args) Tj (,) Tj ( ) Tj .4 .4 .4 rg (**) Tj 0 0 0 rg (kw) Tj (\)) Tj T* ET +Q +Q +Q +Q +Q +q +1 0 0 1 62.69291 282.0236 cm +q +q +1 0 0 1 0 0 cm +q +1 0 0 1 6.6 6.6 cm +q +.662745 .662745 .662745 RG +.5 w +.960784 .960784 .862745 rg +n -6 -6 468.6898 36 re B* +Q +q +BT 1 0 0 1 0 17.71 Tm 12 TL /F3 10 Tf 0 .501961 0 rg (def) Tj /F5 10 Tf 0 0 0 rg ( ) Tj 0 0 1 rg (trace) Tj 0 0 0 rg (\() Tj (f) Tj (\):) Tj T* ( ) Tj /F3 10 Tf 0 .501961 0 rg (return) Tj /F5 10 Tf 0 0 0 rg ( ) Tj (decorator) Tj (\() Tj (_trace) Tj (,) Tj ( ) Tj (f) Tj (\)) Tj T* ET +Q +Q +Q +Q +Q +q +1 0 0 1 62.69291 262.0236 cm +q +0 0 0 rg +BT 1 0 0 1 0 4.82 Tm /F1 10 Tf 12 TL (Here is an example of usage:) Tj T* ET +Q +Q +q +1 0 0 1 62.69291 204.8236 cm +q +q +1 0 0 1 0 0 cm +q +1 0 0 1 6.6 6.6 cm +q +.662745 .662745 .662745 RG +.5 w +.960784 .960784 .862745 rg +n -6 -6 468.6898 48 re B* +Q +q +BT 1 0 0 1 0 29.71 Tm 12 TL /F5 10 Tf .4 .4 .4 rg (>) Tj (>) Tj (>) Tj 0 0 0 rg ( ) Tj .666667 .133333 1 rg (@trace) Tj 0 0 0 rg T* .4 .4 .4 rg (...) Tj 0 0 0 rg ( ) Tj /F3 10 Tf 0 .501961 0 rg (def) Tj /F5 10 Tf 0 0 0 rg ( ) Tj 0 0 1 rg (f1) Tj 0 0 0 rg (\() Tj (x) Tj (\):) Tj T* .4 .4 .4 rg (...) Tj 0 0 0 rg ( ) Tj /F3 10 Tf 0 .501961 0 rg (pass) Tj T* ET +Q +Q +Q +Q +Q +q +1 0 0 1 62.69291 184.8236 cm +q +BT 1 0 0 1 0 4.82 Tm 12 TL /F1 10 Tf 0 0 0 rg (It is immediate to verify that ) Tj /F5 10 Tf (f1 ) Tj /F1 10 Tf (works) Tj T* ET +Q +Q +q +1 0 0 1 62.69291 139.6236 cm +q +q +1 0 0 1 0 0 cm +q +1 0 0 1 6.6 6.6 cm +q +.662745 .662745 .662745 RG +.5 w +.960784 .960784 .862745 rg +n -6 -6 468.6898 36 re B* +Q +q +BT 1 0 0 1 0 17.71 Tm 12 TL /F5 10 Tf .4 .4 .4 rg (>) Tj (>) Tj (>) Tj 0 0 0 rg ( ) Tj (f1) Tj (\() Tj .4 .4 .4 rg (0) Tj 0 0 0 rg (\)) Tj T* (calling) Tj ( ) Tj (f1) Tj ( ) Tj /F3 10 Tf 0 .501961 0 rg (with) Tj /F5 10 Tf 0 0 0 rg ( ) Tj (args) Tj ( ) Tj (\() Tj .4 .4 .4 rg (0) Tj 0 0 0 rg (,\),) Tj ( ) Tj ({}) Tj T* ET +Q +Q +Q +Q +Q +q +1 0 0 1 62.69291 119.6236 cm +q +0 0 0 rg +BT 1 0 0 1 0 4.82 Tm /F1 10 Tf 12 TL (and it that it has the correct signature:) Tj T* ET +Q +Q + +endstream + +endobj +% 'R86': class PDFStream +86 0 obj +% page stream +<< /Length 8829 >> +stream +1 0 0 1 0 0 cm BT /F1 12 Tf 14.4 TL ET +q +1 0 0 1 62.69291 727.8236 cm +q +q +1 0 0 1 0 0 cm +q +1 0 0 1 6.6 6.6 cm +q +.662745 .662745 .662745 RG +.5 w +.960784 .960784 .862745 rg +n -6 -6 468.6898 36 re B* +Q +q +BT 1 0 0 1 0 17.71 Tm 12 TL /F5 10 Tf .4 .4 .4 rg (>) Tj (>) Tj (>) Tj 0 0 0 rg ( ) Tj /F3 10 Tf 0 .501961 0 rg (print) Tj /F5 10 Tf 0 0 0 rg ( ) Tj (getargspec) Tj (\() Tj (f1) Tj (\)) Tj T* (ArgSpec) Tj (\() Tj (args) Tj .4 .4 .4 rg (=) Tj 0 0 0 rg ([) Tj .729412 .129412 .129412 rg ('x') Tj 0 0 0 rg (],) Tj ( ) Tj (varargs) Tj .4 .4 .4 rg (=) Tj 0 .501961 0 rg (None) Tj 0 0 0 rg (,) Tj ( ) Tj (keywords) Tj .4 .4 .4 rg (=) Tj 0 .501961 0 rg (None) Tj 0 0 0 rg (,) Tj ( ) Tj (defaults) Tj .4 .4 .4 rg (=) Tj 0 .501961 0 rg (None) Tj 0 0 0 rg (\)) Tj T* ET +Q +Q +Q +Q +Q +q +1 0 0 1 62.69291 707.8236 cm +q +0 0 0 rg +BT 1 0 0 1 0 4.82 Tm /F1 10 Tf 12 TL (The same decorator works with functions of any signature:) Tj T* ET +Q +Q +q +1 0 0 1 62.69291 579.978 cm +q +q +.988825 0 0 .988825 0 0 cm +q +1 0 0 1 6.6 6.674587 cm +q +.662745 .662745 .662745 RG +.5 w +.960784 .960784 .862745 rg +n -6 -6 474 120 re B* +Q +q +BT 1 0 0 1 0 101.71 Tm 12 TL /F5 10 Tf .4 .4 .4 rg (>) Tj (>) Tj (>) Tj 0 0 0 rg ( ) Tj .666667 .133333 1 rg (@trace) Tj 0 0 0 rg T* .4 .4 .4 rg (...) Tj 0 0 0 rg ( ) Tj /F3 10 Tf 0 .501961 0 rg (def) Tj /F5 10 Tf 0 0 0 rg ( ) Tj 0 0 1 rg (f) Tj 0 0 0 rg (\() Tj (x) Tj (,) Tj ( ) Tj (y) Tj .4 .4 .4 rg (=) Tj (1) Tj 0 0 0 rg (,) Tj ( ) Tj (z) Tj .4 .4 .4 rg (=) Tj (2) Tj 0 0 0 rg (,) Tj ( ) Tj .4 .4 .4 rg (*) Tj 0 0 0 rg (args) Tj (,) Tj ( ) Tj .4 .4 .4 rg (**) Tj 0 0 0 rg (kw) Tj (\):) Tj T* .4 .4 .4 rg (...) Tj 0 0 0 rg ( ) Tj /F3 10 Tf 0 .501961 0 rg (pass) Tj /F5 10 Tf 0 0 0 rg T* T* .4 .4 .4 rg (>) Tj (>) Tj (>) Tj 0 0 0 rg ( ) Tj (f) Tj (\() Tj .4 .4 .4 rg (0) Tj 0 0 0 rg (,) Tj ( ) Tj .4 .4 .4 rg (3) Tj 0 0 0 rg (\)) Tj T* (calling) Tj ( ) Tj (f) Tj ( ) Tj /F3 10 Tf 0 .501961 0 rg (with) Tj /F5 10 Tf 0 0 0 rg ( ) Tj (args) Tj ( ) Tj (\() Tj .4 .4 .4 rg (0) Tj 0 0 0 rg (,) Tj ( ) Tj .4 .4 .4 rg (3) Tj 0 0 0 rg (,) Tj ( ) Tj .4 .4 .4 rg (2) Tj 0 0 0 rg (\),) Tj ( ) Tj ({}) Tj T* T* .4 .4 .4 rg (>) Tj (>) Tj (>) Tj 0 0 0 rg ( ) Tj /F3 10 Tf 0 .501961 0 rg (print) Tj /F5 10 Tf 0 0 0 rg ( ) Tj (getargspec) Tj (\() Tj (f) Tj (\)) Tj T* (ArgSpec) Tj (\() Tj (args) Tj .4 .4 .4 rg (=) Tj 0 0 0 rg ([) Tj .729412 .129412 .129412 rg ('x') Tj 0 0 0 rg (,) Tj ( ) Tj .729412 .129412 .129412 rg ('y') Tj 0 0 0 rg (,) Tj ( ) Tj .729412 .129412 .129412 rg ('z') Tj 0 0 0 rg (],) Tj ( ) Tj (varargs) Tj .4 .4 .4 rg (=) Tj .729412 .129412 .129412 rg ('args') Tj 0 0 0 rg (,) Tj ( ) Tj (keywords) Tj .4 .4 .4 rg (=) Tj .729412 .129412 .129412 rg ('kw') Tj 0 0 0 rg (,) Tj ( ) Tj (defaults) Tj .4 .4 .4 rg (=) Tj 0 0 0 rg (\() Tj .4 .4 .4 rg (1) Tj 0 0 0 rg (,) Tj ( ) Tj .4 .4 .4 rg (2) Tj 0 0 0 rg (\)\)) Tj T* ET +Q +Q +Q +Q +Q +q +1 0 0 1 62.69291 559.978 cm +q +0 0 0 rg +BT 1 0 0 1 0 4.82 Tm /F1 10 Tf 12 TL (That includes even functions with exotic signatures like the following:) Tj T* ET +Q +Q +q +1 0 0 1 62.69291 442.778 cm +q +q +1 0 0 1 0 0 cm +q +1 0 0 1 6.6 6.6 cm +q +.662745 .662745 .662745 RG +.5 w +.960784 .960784 .862745 rg +n -6 -6 468.6898 108 re B* +Q +q +BT 1 0 0 1 0 89.71 Tm 12 TL /F5 10 Tf .4 .4 .4 rg (>) Tj (>) Tj (>) Tj 0 0 0 rg ( ) Tj .666667 .133333 1 rg (@trace) Tj 0 0 0 rg T* .4 .4 .4 rg (...) Tj 0 0 0 rg ( ) Tj /F3 10 Tf 0 .501961 0 rg (def) Tj /F5 10 Tf 0 0 0 rg ( ) Tj 0 0 1 rg (exotic_signature) Tj 0 0 0 rg (\(\() Tj (x) Tj (,) Tj ( ) Tj (y) Tj (\)) Tj .4 .4 .4 rg (=) Tj 0 0 0 rg (\() Tj .4 .4 .4 rg (1) Tj 0 0 0 rg (,) Tj .4 .4 .4 rg (2) Tj 0 0 0 rg (\)\):) Tj ( ) Tj /F3 10 Tf 0 .501961 0 rg (return) Tj /F5 10 Tf 0 0 0 rg ( ) Tj (x) Tj .4 .4 .4 rg (+) Tj 0 0 0 rg (y) Tj T* T* .4 .4 .4 rg (>) Tj (>) Tj (>) Tj 0 0 0 rg ( ) Tj /F3 10 Tf 0 .501961 0 rg (print) Tj /F5 10 Tf 0 0 0 rg ( ) Tj (getargspec) Tj (\() Tj (exotic_signature) Tj (\)) Tj T* (ArgSpec) Tj (\() Tj (args) Tj .4 .4 .4 rg (=) Tj 0 0 0 rg ([[) Tj .729412 .129412 .129412 rg ('x') Tj 0 0 0 rg (,) Tj ( ) Tj .729412 .129412 .129412 rg ('y') Tj 0 0 0 rg (]],) Tj ( ) Tj (varargs) Tj .4 .4 .4 rg (=) Tj 0 .501961 0 rg (None) Tj 0 0 0 rg (,) Tj ( ) Tj (keywords) Tj .4 .4 .4 rg (=) Tj 0 .501961 0 rg (None) Tj 0 0 0 rg (,) Tj ( ) Tj (defaults) Tj .4 .4 .4 rg (=) Tj 0 0 0 rg (\(\() Tj .4 .4 .4 rg (1) Tj 0 0 0 rg (,) Tj ( ) Tj .4 .4 .4 rg (2) Tj 0 0 0 rg (\),\)\)) Tj T* .4 .4 .4 rg (>) Tj (>) Tj (>) Tj 0 0 0 rg ( ) Tj (exotic_signature) Tj (\(\)) Tj T* (calling) Tj ( ) Tj (exotic_signature) Tj ( ) Tj /F3 10 Tf 0 .501961 0 rg (with) Tj /F5 10 Tf 0 0 0 rg ( ) Tj (args) Tj ( ) Tj (\(\() Tj .4 .4 .4 rg (1) Tj 0 0 0 rg (,) Tj ( ) Tj .4 .4 .4 rg (2) Tj 0 0 0 rg (\),\),) Tj ( ) Tj ({}) Tj T* .4 .4 .4 rg (3) Tj T* ET +Q +Q +Q +Q +Q +q +1 0 0 1 62.69291 410.778 cm +q +0 0 0 rg +BT 1 0 0 1 0 16.82 Tm /F1 10 Tf 12 TL .84561 Tw (Notice that the support for exotic signatures has been deprecated in Python 2.6 and removed in Python) Tj T* 0 Tw (3.0.) Tj T* ET +Q +Q +q +1 0 0 1 62.69291 377.778 cm +q +BT 1 0 0 1 0 8.435 Tm 21 TL /F3 17.5 Tf 0 0 0 rg (decorator ) Tj /F2 17.5 Tf (is a decorator) Tj T* ET +Q +Q +q +1 0 0 1 62.69291 275.778 cm +q +BT 1 0 0 1 0 88.82 Tm .643876 Tw 12 TL /F1 10 Tf 0 0 0 rg (It may be annoying to write a caller function \(like the ) Tj /F5 10 Tf (_trace ) Tj /F1 10 Tf (function above\) and then a trivial wrapper) Tj T* 0 Tw 1.803615 Tw (\() Tj /F5 10 Tf (def trace\(f\): return decorator\(_trace, f\)) Tj /F1 10 Tf (\) every time. For this reason, the ) Tj /F5 10 Tf (decorator) Tj T* 0 Tw .334269 Tw /F1 10 Tf (module provides an easy shortcut to convert the caller function into a signature-preserving decorator: you) Tj T* 0 Tw 3.443735 Tw (can just call ) Tj /F5 10 Tf (decorator ) Tj /F1 10 Tf (with a single argument. In our example you can just write ) Tj /F5 10 Tf (trace =) Tj T* 0 Tw 1.056342 Tw (decorator\(_trace\)) Tj /F1 10 Tf (. The ) Tj /F5 10 Tf (decorator ) Tj /F1 10 Tf (function can also be used as a signature-changing decorator,) Tj T* 0 Tw 3.177752 Tw (just as ) Tj /F5 10 Tf (classmethod ) Tj /F1 10 Tf (and ) Tj /F5 10 Tf (staticmethod) Tj /F1 10 Tf (. However, ) Tj /F5 10 Tf (classmethod ) Tj /F1 10 Tf (and ) Tj /F5 10 Tf (staticmethod ) Tj /F1 10 Tf (return) Tj T* 0 Tw 1.693615 Tw (generic objects which are not callable, while ) Tj /F5 10 Tf (decorator ) Tj /F1 10 Tf (returns signature-preserving decorators, i.e.) Tj T* 0 Tw (functions of a single argument. For instance, you can write directly) Tj T* ET +Q +Q +q +1 0 0 1 62.69291 206.578 cm +q +q +1 0 0 1 0 0 cm +q +1 0 0 1 6.6 6.6 cm +q +.662745 .662745 .662745 RG +.5 w +.960784 .960784 .862745 rg +n -6 -6 468.6898 60 re B* +Q +q +BT 1 0 0 1 0 41.71 Tm 12 TL /F5 10 Tf .4 .4 .4 rg (>) Tj (>) Tj (>) Tj 0 0 0 rg ( ) Tj .666667 .133333 1 rg (@decorator) Tj 0 0 0 rg T* .4 .4 .4 rg (...) Tj 0 0 0 rg ( ) Tj /F3 10 Tf 0 .501961 0 rg (def) Tj /F5 10 Tf 0 0 0 rg ( ) Tj 0 0 1 rg (trace) Tj 0 0 0 rg (\() Tj (f) Tj (,) Tj ( ) Tj .4 .4 .4 rg (*) Tj 0 0 0 rg (args) Tj (,) Tj ( ) Tj .4 .4 .4 rg (**) Tj 0 0 0 rg (kw) Tj (\):) Tj T* .4 .4 .4 rg (...) Tj 0 0 0 rg ( ) Tj /F3 10 Tf 0 .501961 0 rg (print) Tj /F5 10 Tf 0 0 0 rg ( ) Tj .729412 .129412 .129412 rg ("calling ) Tj /F3 10 Tf .733333 .4 .533333 rg (%s) Tj /F5 10 Tf .729412 .129412 .129412 rg ( with args ) Tj /F3 10 Tf .733333 .4 .533333 rg (%s) Tj /F5 10 Tf .729412 .129412 .129412 rg (, ) Tj /F3 10 Tf .733333 .4 .533333 rg (%s) Tj /F5 10 Tf .729412 .129412 .129412 rg (") Tj 0 0 0 rg ( ) Tj .4 .4 .4 rg (%) Tj 0 0 0 rg ( ) Tj (\() Tj (f) Tj .4 .4 .4 rg (.) Tj 0 0 0 rg (func_name) Tj (,) Tj ( ) Tj (args) Tj (,) Tj ( ) Tj (kw) Tj (\)) Tj T* .4 .4 .4 rg (...) Tj 0 0 0 rg ( ) Tj /F3 10 Tf 0 .501961 0 rg (return) Tj /F5 10 Tf 0 0 0 rg ( ) Tj (f) Tj (\() Tj .4 .4 .4 rg (*) Tj 0 0 0 rg (args) Tj (,) Tj ( ) Tj .4 .4 .4 rg (**) Tj 0 0 0 rg (kw) Tj (\)) Tj T* ET +Q +Q +Q +Q +Q +q +1 0 0 1 62.69291 174.578 cm +q +BT 1 0 0 1 0 16.82 Tm 1.806654 Tw 12 TL /F1 10 Tf 0 0 0 rg (and now ) Tj /F5 10 Tf (trace ) Tj /F1 10 Tf (will be a decorator. Actually ) Tj /F5 10 Tf (trace ) Tj /F1 10 Tf (is a ) Tj /F5 10 Tf (partial ) Tj /F1 10 Tf (object which can be used as a) Tj T* 0 Tw (decorator:) Tj T* ET +Q +Q +q +1 0 0 1 62.69291 129.378 cm +q +q +1 0 0 1 0 0 cm +q +1 0 0 1 6.6 6.6 cm +q +.662745 .662745 .662745 RG +.5 w +.960784 .960784 .862745 rg +n -6 -6 468.6898 36 re B* +Q +q +BT 1 0 0 1 0 17.71 Tm 12 TL /F5 10 Tf .4 .4 .4 rg (>) Tj (>) Tj (>) Tj 0 0 0 rg ( ) Tj (trace) Tj T* .4 .4 .4 rg (<) Tj 0 0 0 rg (function) Tj ( ) Tj (trace) Tj ( ) Tj (at) Tj ( ) Tj .4 .4 .4 rg (0) Tj 0 0 0 rg (x) Tj .4 .4 .4 rg (...) Tj (>) Tj T* ET +Q +Q +Q +Q +Q +q +1 0 0 1 62.69291 109.378 cm +q +0 0 0 rg +BT 1 0 0 1 0 4.82 Tm /F1 10 Tf 12 TL (Here is an example of usage:) Tj T* ET +Q +Q + +endstream + +endobj +% 'R87': class PDFStream +87 0 obj +% page stream +<< /Length 7175 >> +stream +1 0 0 1 0 0 cm BT /F1 12 Tf 14.4 TL ET +q +1 0 0 1 62.69291 691.8236 cm +q +q +1 0 0 1 0 0 cm +q +1 0 0 1 6.6 6.6 cm +q +.662745 .662745 .662745 RG +.5 w +.960784 .960784 .862745 rg +n -6 -6 468.6898 72 re B* +Q +q +BT 1 0 0 1 0 53.71 Tm 12 TL /F5 10 Tf .4 .4 .4 rg (>) Tj (>) Tj (>) Tj 0 0 0 rg ( ) Tj .666667 .133333 1 rg (@trace) Tj 0 0 0 rg T* .4 .4 .4 rg (...) Tj 0 0 0 rg ( ) Tj /F3 10 Tf 0 .501961 0 rg (def) Tj /F5 10 Tf 0 0 0 rg ( ) Tj 0 0 1 rg (func) Tj 0 0 0 rg (\(\):) Tj ( ) Tj /F3 10 Tf 0 .501961 0 rg (pass) Tj /F5 10 Tf 0 0 0 rg T* T* .4 .4 .4 rg (>) Tj (>) Tj (>) Tj 0 0 0 rg ( ) Tj (func) Tj (\(\)) Tj T* (calling) Tj ( ) Tj (func) Tj ( ) Tj /F3 10 Tf 0 .501961 0 rg (with) Tj /F5 10 Tf 0 0 0 rg ( ) Tj (args) Tj ( ) Tj (\(\),) Tj ( ) Tj ({}) Tj T* ET +Q +Q +Q +Q +Q +q +1 0 0 1 62.69291 659.8236 cm +q +BT 1 0 0 1 0 16.82 Tm 2.44686 Tw 12 TL /F1 10 Tf 0 0 0 rg (If you are using an old Python version \(Python 2.4\) the ) Tj /F5 10 Tf (decorator ) Tj /F1 10 Tf (module provides a poor man) Tj T* 0 Tw (replacement for ) Tj /F5 10 Tf (functools.partial) Tj /F1 10 Tf (.) Tj T* ET +Q +Q +q +1 0 0 1 62.69291 626.8236 cm +q +BT 1 0 0 1 0 8.435 Tm 21 TL /F3 17.5 Tf 0 0 0 rg (blocking) Tj T* ET +Q +Q +q +1 0 0 1 62.69291 584.8236 cm +q +BT 1 0 0 1 0 28.82 Tm 1.224692 Tw 12 TL /F1 10 Tf 0 0 0 rg (Sometimes one has to deal with blocking resources, such as ) Tj /F5 10 Tf (stdin) Tj /F1 10 Tf (, and sometimes it is best to have) Tj T* 0 Tw .266235 Tw (back a "busy" message than to block everything. This behavior can be implemented with a suitable family) Tj T* 0 Tw (of decorators, where the parameter is the busy message:) Tj T* ET +Q +Q +q +1 0 0 1 62.69291 407.6236 cm +q +q +1 0 0 1 0 0 cm +q +1 0 0 1 6.6 6.6 cm +q +.662745 .662745 .662745 RG +.5 w +.960784 .960784 .862745 rg +n -6 -6 468.6898 168 re B* +Q +q +BT 1 0 0 1 0 149.71 Tm 12 TL /F3 10 Tf 0 .501961 0 rg (def) Tj /F5 10 Tf 0 0 0 rg ( ) Tj 0 0 1 rg (blocking) Tj 0 0 0 rg (\() Tj (not_avail) Tj (\):) Tj T* ( ) Tj /F3 10 Tf 0 .501961 0 rg (def) Tj /F5 10 Tf 0 0 0 rg ( ) Tj 0 0 1 rg (blocking) Tj 0 0 0 rg (\() Tj (f) Tj (,) Tj ( ) Tj .4 .4 .4 rg (*) Tj 0 0 0 rg (args) Tj (,) Tj ( ) Tj .4 .4 .4 rg (**) Tj 0 0 0 rg (kw) Tj (\):) Tj T* ( ) Tj /F3 10 Tf 0 .501961 0 rg (if) Tj /F5 10 Tf 0 0 0 rg ( ) Tj /F3 10 Tf .666667 .133333 1 rg (not) Tj /F5 10 Tf 0 0 0 rg ( ) Tj 0 .501961 0 rg (hasattr) Tj 0 0 0 rg (\() Tj (f) Tj (,) Tj ( ) Tj .729412 .129412 .129412 rg ("thread") Tj 0 0 0 rg (\):) Tj ( ) Tj /F7 10 Tf .25098 .501961 .501961 rg (# no thread running) Tj /F5 10 Tf 0 0 0 rg T* ( ) Tj /F3 10 Tf 0 .501961 0 rg (def) Tj /F5 10 Tf 0 0 0 rg ( ) Tj 0 0 1 rg (set_result) Tj 0 0 0 rg (\(\):) Tj ( ) Tj (f) Tj .4 .4 .4 rg (.) Tj 0 0 0 rg (result) Tj ( ) Tj .4 .4 .4 rg (=) Tj 0 0 0 rg ( ) Tj (f) Tj (\() Tj .4 .4 .4 rg (*) Tj 0 0 0 rg (args) Tj (,) Tj ( ) Tj .4 .4 .4 rg (**) Tj 0 0 0 rg (kw) Tj (\)) Tj T* ( ) Tj (f) Tj .4 .4 .4 rg (.) Tj 0 0 0 rg (thread) Tj ( ) Tj .4 .4 .4 rg (=) Tj 0 0 0 rg ( ) Tj (threading) Tj .4 .4 .4 rg (.) Tj 0 0 0 rg (Thread) Tj (\() Tj 0 .501961 0 rg (None) Tj 0 0 0 rg (,) Tj ( ) Tj (set_result) Tj (\)) Tj T* ( ) Tj (f) Tj .4 .4 .4 rg (.) Tj 0 0 0 rg (thread) Tj .4 .4 .4 rg (.) Tj 0 0 0 rg (start) Tj (\(\)) Tj T* ( ) Tj /F3 10 Tf 0 .501961 0 rg (return) Tj /F5 10 Tf 0 0 0 rg ( ) Tj (not_avail) Tj T* ( ) Tj /F3 10 Tf 0 .501961 0 rg (elif) Tj /F5 10 Tf 0 0 0 rg ( ) Tj (f) Tj .4 .4 .4 rg (.) Tj 0 0 0 rg (thread) Tj .4 .4 .4 rg (.) Tj 0 0 0 rg (isAlive) Tj (\(\):) Tj T* ( ) Tj /F3 10 Tf 0 .501961 0 rg (return) Tj /F5 10 Tf 0 0 0 rg ( ) Tj (not_avail) Tj T* ( ) Tj /F3 10 Tf 0 .501961 0 rg (else) Tj /F5 10 Tf 0 0 0 rg (:) Tj ( ) Tj /F7 10 Tf .25098 .501961 .501961 rg (# the thread is ended, return the stored result) Tj /F5 10 Tf 0 0 0 rg T* ( ) Tj /F3 10 Tf 0 .501961 0 rg (del) Tj /F5 10 Tf 0 0 0 rg ( ) Tj (f) Tj .4 .4 .4 rg (.) Tj 0 0 0 rg (thread) Tj T* ( ) Tj /F3 10 Tf 0 .501961 0 rg (return) Tj /F5 10 Tf 0 0 0 rg ( ) Tj (f) Tj .4 .4 .4 rg (.) Tj 0 0 0 rg (result) Tj T* ( ) Tj /F3 10 Tf 0 .501961 0 rg (return) Tj /F5 10 Tf 0 0 0 rg ( ) Tj (decorator) Tj (\() Tj (blocking) Tj (\)) Tj T* ET +Q +Q +Q +Q +Q +q +1 0 0 1 62.69291 375.6236 cm +q +BT 1 0 0 1 0 16.82 Tm 1.010651 Tw 12 TL /F1 10 Tf 0 0 0 rg (Functions decorated with ) Tj /F5 10 Tf (blocking ) Tj /F1 10 Tf (will return a busy message if the resource is unavailable, and the) Tj T* 0 Tw (intended result if the resource is available. For instance:) Tj T* ET +Q +Q +q +1 0 0 1 62.69291 126.4236 cm +q +q +1 0 0 1 0 0 cm +q +1 0 0 1 6.6 6.6 cm +q +.662745 .662745 .662745 RG +.5 w +.960784 .960784 .862745 rg +n -6 -6 468.6898 240 re B* +Q +q +BT 1 0 0 1 0 221.71 Tm 12 TL /F5 10 Tf .4 .4 .4 rg (>) Tj (>) Tj (>) Tj 0 0 0 rg ( ) Tj .666667 .133333 1 rg (@blocking) Tj 0 0 0 rg (\() Tj .729412 .129412 .129412 rg ("Please wait ...") Tj 0 0 0 rg (\)) Tj T* .4 .4 .4 rg (...) Tj 0 0 0 rg ( ) Tj /F3 10 Tf 0 .501961 0 rg (def) Tj /F5 10 Tf 0 0 0 rg ( ) Tj 0 0 1 rg (read_data) Tj 0 0 0 rg (\(\):) Tj T* .4 .4 .4 rg (...) Tj 0 0 0 rg ( ) Tj (time) Tj .4 .4 .4 rg (.) Tj 0 0 0 rg (sleep) Tj (\() Tj .4 .4 .4 rg (3) Tj 0 0 0 rg (\)) Tj ( ) Tj /F7 10 Tf .25098 .501961 .501961 rg (# simulate a blocking resource) Tj /F5 10 Tf 0 0 0 rg T* .4 .4 .4 rg (...) Tj 0 0 0 rg ( ) Tj /F3 10 Tf 0 .501961 0 rg (return) Tj /F5 10 Tf 0 0 0 rg ( ) Tj .729412 .129412 .129412 rg ("some data") Tj 0 0 0 rg T* T* .4 .4 .4 rg (>) Tj (>) Tj (>) Tj 0 0 0 rg ( ) Tj /F3 10 Tf 0 .501961 0 rg (print) Tj /F5 10 Tf 0 0 0 rg ( ) Tj (read_data) Tj (\(\)) Tj ( ) Tj /F7 10 Tf .25098 .501961 .501961 rg (# data is not available yet) Tj /F5 10 Tf 0 0 0 rg T* (Please) Tj ( ) Tj (wait) Tj ( ) Tj .4 .4 .4 rg (...) Tj 0 0 0 rg T* T* .4 .4 .4 rg (>) Tj (>) Tj (>) Tj 0 0 0 rg ( ) Tj (time) Tj .4 .4 .4 rg (.) Tj 0 0 0 rg (sleep) Tj (\() Tj .4 .4 .4 rg (1) Tj 0 0 0 rg (\)) Tj T* .4 .4 .4 rg (>) Tj (>) Tj (>) Tj 0 0 0 rg ( ) Tj /F3 10 Tf 0 .501961 0 rg (print) Tj /F5 10 Tf 0 0 0 rg ( ) Tj (read_data) Tj (\(\)) Tj ( ) Tj /F7 10 Tf .25098 .501961 .501961 rg (# data is not available yet) Tj /F5 10 Tf 0 0 0 rg T* (Please) Tj ( ) Tj (wait) Tj ( ) Tj .4 .4 .4 rg (...) Tj 0 0 0 rg T* T* .4 .4 .4 rg (>) Tj (>) Tj (>) Tj 0 0 0 rg ( ) Tj (time) Tj .4 .4 .4 rg (.) Tj 0 0 0 rg (sleep) Tj (\() Tj .4 .4 .4 rg (1) Tj 0 0 0 rg (\)) Tj T* .4 .4 .4 rg (>) Tj (>) Tj (>) Tj 0 0 0 rg ( ) Tj /F3 10 Tf 0 .501961 0 rg (print) Tj /F5 10 Tf 0 0 0 rg ( ) Tj (read_data) Tj (\(\)) Tj ( ) Tj /F7 10 Tf .25098 .501961 .501961 rg (# data is not available yet) Tj /F5 10 Tf 0 0 0 rg T* (Please) Tj ( ) Tj (wait) Tj ( ) Tj .4 .4 .4 rg (...) Tj 0 0 0 rg T* T* .4 .4 .4 rg (>) Tj (>) Tj (>) Tj 0 0 0 rg ( ) Tj (time) Tj .4 .4 .4 rg (.) Tj 0 0 0 rg (sleep) Tj (\() Tj .4 .4 .4 rg (1.1) Tj 0 0 0 rg (\)) Tj ( ) Tj /F7 10 Tf .25098 .501961 .501961 rg (# after 3.1 seconds, data is available) Tj /F5 10 Tf 0 0 0 rg T* .4 .4 .4 rg (>) Tj (>) Tj (>) Tj 0 0 0 rg ( ) Tj /F3 10 Tf 0 .501961 0 rg (print) Tj /F5 10 Tf 0 0 0 rg ( ) Tj (read_data) Tj (\(\)) Tj T* (some) Tj ( ) Tj (data) Tj T* ET +Q +Q +Q +Q +Q + +endstream + +endobj +% 'R88': class PDFStream +88 0 obj +% page stream +<< /Length 6889 >> +stream +1 0 0 1 0 0 cm BT /F1 12 Tf 14.4 TL ET +q +1 0 0 1 62.69291 744.0236 cm +q +BT 1 0 0 1 0 8.435 Tm 21 TL /F3 17.5 Tf 0 0 0 rg (async) Tj T* ET +Q +Q +q +1 0 0 1 62.69291 678.0236 cm +q +BT 1 0 0 1 0 52.82 Tm 1.647485 Tw 12 TL /F1 10 Tf 0 0 0 rg (We have just seen an examples of a simple decorator factory, implemented as a function returning a) Tj T* 0 Tw .29784 Tw (decorator. For more complex situations, it is more convenient to implement decorator factories as classes) Tj T* 0 Tw .657674 Tw (returning callable objects that can be used as signature-preserving decorators. The suggested pattern to) Tj T* 0 Tw 2.109398 Tw (do that is to introduce a helper method ) Tj /F5 10 Tf (call\(self, func, *args, **kw\) ) Tj /F1 10 Tf (and to call it in the) Tj T* 0 Tw /F5 10 Tf (__call__\(self, func\) ) Tj /F1 10 Tf (method.) Tj T* ET +Q +Q +q +1 0 0 1 62.69291 624.0236 cm +q +BT 1 0 0 1 0 40.82 Tm .166654 Tw 12 TL /F1 10 Tf 0 0 0 rg (As an example, here I show a decorator which is able to convert a blocking function into an asynchronous) Tj T* 0 Tw .437633 Tw (function. The function, when called, is executed in a separate thread. Moreover, it is possible to set three) Tj T* 0 Tw .074597 Tw (callbacks ) Tj /F5 10 Tf (on_success) Tj /F1 10 Tf (, ) Tj /F5 10 Tf (on_failure ) Tj /F1 10 Tf (and ) Tj /F5 10 Tf (on_closing) Tj /F1 10 Tf (, to specify how to manage the function call. The) Tj T* 0 Tw (implementation is the following:) Tj T* ET +Q +Q +q +1 0 0 1 62.69291 566.8236 cm +q +q +1 0 0 1 0 0 cm +q +1 0 0 1 6.6 6.6 cm +q +.662745 .662745 .662745 RG +.5 w +.960784 .960784 .862745 rg +n -6 -6 468.6898 48 re B* +Q +q +BT 1 0 0 1 0 29.71 Tm 12 TL /F3 10 Tf 0 .501961 0 rg (def) Tj /F5 10 Tf 0 0 0 rg ( ) Tj 0 0 1 rg (on_success) Tj 0 0 0 rg (\() Tj (result) Tj (\):) Tj ( ) Tj /F7 10 Tf .25098 .501961 .501961 rg (# default implementation) Tj /F5 10 Tf 0 0 0 rg T* ( ) Tj .729412 .129412 .129412 rg ("Called on the result of the function") Tj 0 0 0 rg T* ( ) Tj /F3 10 Tf 0 .501961 0 rg (return) Tj /F5 10 Tf 0 0 0 rg ( ) Tj (result) Tj T* ET +Q +Q +Q +Q +Q +q +1 0 0 1 62.69291 509.6236 cm +q +q +1 0 0 1 0 0 cm +q +1 0 0 1 6.6 6.6 cm +q +.662745 .662745 .662745 RG +.5 w +.960784 .960784 .862745 rg +n -6 -6 468.6898 48 re B* +Q +q +BT 1 0 0 1 0 29.71 Tm 12 TL /F3 10 Tf 0 .501961 0 rg (def) Tj /F5 10 Tf 0 0 0 rg ( ) Tj 0 0 1 rg (on_failure) Tj 0 0 0 rg (\() Tj (exc_info) Tj (\):) Tj ( ) Tj /F7 10 Tf .25098 .501961 .501961 rg (# default implementation) Tj /F5 10 Tf 0 0 0 rg T* ( ) Tj .729412 .129412 .129412 rg ("Called if the function fails") Tj 0 0 0 rg T* ( ) Tj /F3 10 Tf 0 .501961 0 rg (pass) Tj T* ET +Q +Q +Q +Q +Q +q +1 0 0 1 62.69291 452.4236 cm +q +q +1 0 0 1 0 0 cm +q +1 0 0 1 6.6 6.6 cm +q +.662745 .662745 .662745 RG +.5 w +.960784 .960784 .862745 rg +n -6 -6 468.6898 48 re B* +Q +q +BT 1 0 0 1 0 29.71 Tm 12 TL /F3 10 Tf 0 .501961 0 rg (def) Tj /F5 10 Tf 0 0 0 rg ( ) Tj 0 0 1 rg (on_closing) Tj 0 0 0 rg (\(\):) Tj ( ) Tj /F7 10 Tf .25098 .501961 .501961 rg (# default implementation) Tj /F5 10 Tf 0 0 0 rg T* ( ) Tj .729412 .129412 .129412 rg ("Called at the end, both in case of success and failure") Tj 0 0 0 rg T* ( ) Tj /F3 10 Tf 0 .501961 0 rg (pass) Tj T* ET +Q +Q +Q +Q +Q +q +1 0 0 1 62.69291 83.22362 cm +q +q +1 0 0 1 0 0 cm +q +1 0 0 1 6.6 6.6 cm +q +.662745 .662745 .662745 RG +.5 w +.960784 .960784 .862745 rg +n -6 -6 468.6898 360 re B* +Q +q +BT 1 0 0 1 0 341.71 Tm 12 TL /F3 10 Tf 0 .501961 0 rg (class) Tj /F5 10 Tf 0 0 0 rg ( ) Tj /F3 10 Tf 0 0 1 rg (Async) Tj /F5 10 Tf 0 0 0 rg (\() Tj 0 .501961 0 rg (object) Tj 0 0 0 rg (\):) Tj T* ( ) Tj /F7 10 Tf .729412 .129412 .129412 rg (""") Tj T* ( A decorator converting blocking functions into asynchronous) Tj T* ( functions, by using threads or processes. Examples:) Tj T* T* ( async_with_threads = Async\(threading.Thread\)) Tj T* ( async_with_processes = Async\(multiprocessing.Process\)) Tj T* ( """) Tj /F5 10 Tf 0 0 0 rg T* T* ( ) Tj /F3 10 Tf 0 .501961 0 rg (def) Tj /F5 10 Tf 0 0 0 rg ( ) Tj 0 0 1 rg (__init__) Tj 0 0 0 rg (\() Tj 0 .501961 0 rg (self) Tj 0 0 0 rg (,) Tj ( ) Tj (threadfactory) Tj (\):) Tj T* ( ) Tj 0 .501961 0 rg (self) Tj .4 .4 .4 rg (.) Tj 0 0 0 rg (threadfactory) Tj ( ) Tj .4 .4 .4 rg (=) Tj 0 0 0 rg ( ) Tj (threadfactory) Tj T* T* ( ) Tj /F3 10 Tf 0 .501961 0 rg (def) Tj /F5 10 Tf 0 0 0 rg ( ) Tj 0 0 1 rg (__call__) Tj 0 0 0 rg (\() Tj 0 .501961 0 rg (self) Tj 0 0 0 rg (,) Tj ( ) Tj (func) Tj (,) Tj ( ) Tj (on_success) Tj .4 .4 .4 rg (=) Tj 0 0 0 rg (on_success) Tj (,) Tj T* ( ) Tj (on_failure) Tj .4 .4 .4 rg (=) Tj 0 0 0 rg (on_failure) Tj (,) Tj ( ) Tj (on_closing) Tj .4 .4 .4 rg (=) Tj 0 0 0 rg (on_closing) Tj (\):) Tj T* ( ) Tj /F7 10 Tf .25098 .501961 .501961 rg (# every decorated function has its own independent thread counter) Tj /F5 10 Tf 0 0 0 rg T* ( ) Tj (func) Tj .4 .4 .4 rg (.) Tj 0 0 0 rg (counter) Tj ( ) Tj .4 .4 .4 rg (=) Tj 0 0 0 rg ( ) Tj (itertools) Tj .4 .4 .4 rg (.) Tj 0 0 0 rg (count) Tj (\() Tj .4 .4 .4 rg (1) Tj 0 0 0 rg (\)) Tj T* ( ) Tj (func) Tj .4 .4 .4 rg (.) Tj 0 0 0 rg (on_success) Tj ( ) Tj .4 .4 .4 rg (=) Tj 0 0 0 rg ( ) Tj (on_success) Tj T* ( ) Tj (func) Tj .4 .4 .4 rg (.) Tj 0 0 0 rg (on_failure) Tj ( ) Tj .4 .4 .4 rg (=) Tj 0 0 0 rg ( ) Tj (on_failure) Tj T* ( ) Tj (func) Tj .4 .4 .4 rg (.) Tj 0 0 0 rg (on_closing) Tj ( ) Tj .4 .4 .4 rg (=) Tj 0 0 0 rg ( ) Tj (on_closing) Tj T* ( ) Tj /F3 10 Tf 0 .501961 0 rg (return) Tj /F5 10 Tf 0 0 0 rg ( ) Tj (decorator) Tj (\() Tj 0 .501961 0 rg (self) Tj .4 .4 .4 rg (.) Tj 0 0 0 rg (call) Tj (,) Tj ( ) Tj (func) Tj (\)) Tj T* T* ( ) Tj /F3 10 Tf 0 .501961 0 rg (def) Tj /F5 10 Tf 0 0 0 rg ( ) Tj 0 0 1 rg (call) Tj 0 0 0 rg (\() Tj 0 .501961 0 rg (self) Tj 0 0 0 rg (,) Tj ( ) Tj (func) Tj (,) Tj ( ) Tj .4 .4 .4 rg (*) Tj 0 0 0 rg (args) Tj (,) Tj ( ) Tj .4 .4 .4 rg (**) Tj 0 0 0 rg (kw) Tj (\):) Tj T* ( ) Tj /F3 10 Tf 0 .501961 0 rg (def) Tj /F5 10 Tf 0 0 0 rg ( ) Tj 0 0 1 rg (func_wrapper) Tj 0 0 0 rg (\(\):) Tj T* ( ) Tj /F3 10 Tf 0 .501961 0 rg (try) Tj /F5 10 Tf 0 0 0 rg (:) Tj T* ( ) Tj (result) Tj ( ) Tj .4 .4 .4 rg (=) Tj 0 0 0 rg ( ) Tj (func) Tj (\() Tj .4 .4 .4 rg (*) Tj 0 0 0 rg (args) Tj (,) Tj ( ) Tj .4 .4 .4 rg (**) Tj 0 0 0 rg (kw) Tj (\)) Tj T* ( ) Tj /F3 10 Tf 0 .501961 0 rg (except) Tj /F5 10 Tf 0 0 0 rg (:) Tj T* ( ) Tj (func) Tj .4 .4 .4 rg (.) Tj 0 0 0 rg (on_failure) Tj (\() Tj (sys) Tj .4 .4 .4 rg (.) Tj 0 0 0 rg (exc_info) Tj (\(\)\)) Tj T* ( ) Tj /F3 10 Tf 0 .501961 0 rg (else) Tj /F5 10 Tf 0 0 0 rg (:) Tj T* ( ) Tj /F3 10 Tf 0 .501961 0 rg (return) Tj /F5 10 Tf 0 0 0 rg ( ) Tj (func) Tj .4 .4 .4 rg (.) Tj 0 0 0 rg (on_success) Tj (\() Tj (result) Tj (\)) Tj T* ET +Q +Q +Q +Q +Q + +endstream + +endobj +% 'R89': class PDFStream +89 0 obj +% page stream +<< /Length 7268 >> +stream +1 0 0 1 0 0 cm BT /F1 12 Tf 14.4 TL ET +q +1 0 0 1 62.69291 679.8236 cm +q +q +1 0 0 1 0 0 cm +q +1 0 0 1 6.6 6.6 cm +q +.662745 .662745 .662745 RG +.5 w +.960784 .960784 .862745 rg +n -6 -6 468.6898 84 re B* +Q +q +BT 1 0 0 1 0 65.71 Tm 12 TL /F5 10 Tf 0 0 0 rg ( ) Tj /F3 10 Tf 0 .501961 0 rg (finally) Tj /F5 10 Tf 0 0 0 rg (:) Tj T* ( ) Tj (func) Tj .4 .4 .4 rg (.) Tj 0 0 0 rg (on_closing) Tj (\(\)) Tj T* ( ) Tj (name) Tj ( ) Tj .4 .4 .4 rg (=) Tj 0 0 0 rg ( ) Tj .729412 .129412 .129412 rg (') Tj /F3 10 Tf .733333 .4 .533333 rg (%s) Tj /F5 10 Tf .729412 .129412 .129412 rg (-) Tj /F3 10 Tf .733333 .4 .533333 rg (%s) Tj /F5 10 Tf .729412 .129412 .129412 rg (') Tj 0 0 0 rg ( ) Tj .4 .4 .4 rg (%) Tj 0 0 0 rg ( ) Tj (\() Tj (func) Tj .4 .4 .4 rg (.) Tj 0 0 0 rg (__name__) Tj (,) Tj ( ) Tj (func) Tj .4 .4 .4 rg (.) Tj 0 0 0 rg (counter) Tj .4 .4 .4 rg (.) Tj 0 0 0 rg (next) Tj (\(\)\)) Tj T* ( ) Tj (thread) Tj ( ) Tj .4 .4 .4 rg (=) Tj 0 0 0 rg ( ) Tj 0 .501961 0 rg (self) Tj .4 .4 .4 rg (.) Tj 0 0 0 rg (threadfactory) Tj (\() Tj 0 .501961 0 rg (None) Tj 0 0 0 rg (,) Tj ( ) Tj (func_wrapper) Tj (,) Tj ( ) Tj (name) Tj (\)) Tj T* ( ) Tj (thread) Tj .4 .4 .4 rg (.) Tj 0 0 0 rg (start) Tj (\(\)) Tj T* ( ) Tj /F3 10 Tf 0 .501961 0 rg (return) Tj /F5 10 Tf 0 0 0 rg ( ) Tj (thread) Tj T* ET +Q +Q +Q +Q +Q +q +1 0 0 1 62.69291 647.8236 cm +q +BT 1 0 0 1 0 16.82 Tm .865984 Tw 12 TL /F1 10 Tf 0 0 0 rg (The decorated function returns the current execution thread, which can be stored and checked later, for) Tj T* 0 Tw (instance to verify that the thread ) Tj /F5 10 Tf (.isAlive\(\)) Tj /F1 10 Tf (.) Tj T* ET +Q +Q +q +1 0 0 1 62.69291 605.8236 cm +q +0 0 0 rg +BT 1 0 0 1 0 28.82 Tm /F1 10 Tf 12 TL .691654 Tw (Here is an example of usage. Suppose one wants to write some data to an external resource which can) Tj T* 0 Tw .21683 Tw (be accessed by a single user at once \(for instance a printer\). Then the access to the writing function must) Tj T* 0 Tw (be locked. Here is a minimalistic example:) Tj T* ET +Q +Q +q +1 0 0 1 62.69291 452.6236 cm +q +q +1 0 0 1 0 0 cm +q +1 0 0 1 6.6 6.6 cm +q +.662745 .662745 .662745 RG +.5 w +.960784 .960784 .862745 rg +n -6 -6 468.6898 144 re B* +Q +q +BT 1 0 0 1 0 125.71 Tm 12 TL /F5 10 Tf .4 .4 .4 rg (>) Tj (>) Tj (>) Tj 0 0 0 rg ( ) Tj (async) Tj ( ) Tj .4 .4 .4 rg (=) Tj 0 0 0 rg ( ) Tj (Async) Tj (\() Tj (threading) Tj .4 .4 .4 rg (.) Tj 0 0 0 rg (Thread) Tj (\)) Tj T* T* .4 .4 .4 rg (>) Tj (>) Tj (>) Tj 0 0 0 rg ( ) Tj (datalist) Tj ( ) Tj .4 .4 .4 rg (=) Tj 0 0 0 rg ( ) Tj ([]) Tj ( ) Tj /F7 10 Tf .25098 .501961 .501961 rg (# for simplicity the written data are stored into a list.) Tj /F5 10 Tf 0 0 0 rg T* T* .4 .4 .4 rg (>) Tj (>) Tj (>) Tj 0 0 0 rg ( ) Tj .666667 .133333 1 rg (@async) Tj 0 0 0 rg T* .4 .4 .4 rg (...) Tj 0 0 0 rg ( ) Tj /F3 10 Tf 0 .501961 0 rg (def) Tj /F5 10 Tf 0 0 0 rg ( ) Tj 0 0 1 rg (write) Tj 0 0 0 rg (\() Tj (data) Tj (\):) Tj T* .4 .4 .4 rg (...) Tj 0 0 0 rg ( ) Tj /F7 10 Tf .25098 .501961 .501961 rg (# append data to the datalist by locking) Tj /F5 10 Tf 0 0 0 rg T* .4 .4 .4 rg (...) Tj 0 0 0 rg ( ) Tj /F3 10 Tf 0 .501961 0 rg (with) Tj /F5 10 Tf 0 0 0 rg ( ) Tj (threading) Tj .4 .4 .4 rg (.) Tj 0 0 0 rg (Lock) Tj (\(\):) Tj T* .4 .4 .4 rg (...) Tj 0 0 0 rg ( ) Tj (time) Tj .4 .4 .4 rg (.) Tj 0 0 0 rg (sleep) Tj (\() Tj .4 .4 .4 rg (1) Tj 0 0 0 rg (\)) Tj ( ) Tj /F7 10 Tf .25098 .501961 .501961 rg (# emulate some long running operation) Tj /F5 10 Tf 0 0 0 rg T* .4 .4 .4 rg (...) Tj 0 0 0 rg ( ) Tj (datalist) Tj .4 .4 .4 rg (.) Tj 0 0 0 rg (append) Tj (\() Tj (data) Tj (\)) Tj T* .4 .4 .4 rg (...) Tj 0 0 0 rg ( ) Tj /F7 10 Tf .25098 .501961 .501961 rg (# other operations not requiring a lock here) Tj T* ET +Q +Q +Q +Q +Q +q +1 0 0 1 62.69291 420.6236 cm +q +BT 1 0 0 1 0 16.82 Tm .905868 Tw 12 TL /F1 10 Tf 0 0 0 rg (Each call to ) Tj /F5 10 Tf (write ) Tj /F1 10 Tf (will create a new writer thread, but there will be no synchronization problems since) Tj T* 0 Tw /F5 10 Tf (write ) Tj /F1 10 Tf (is locked.) Tj T* ET +Q +Q +q +1 0 0 1 62.69291 255.4236 cm +q +q +1 0 0 1 0 0 cm +q +1 0 0 1 6.6 6.6 cm +q +.662745 .662745 .662745 RG +.5 w +.960784 .960784 .862745 rg +n -6 -6 468.6898 156 re B* +Q +q +BT 1 0 0 1 0 137.71 Tm 12 TL /F5 10 Tf .4 .4 .4 rg (>) Tj (>) Tj (>) Tj 0 0 0 rg ( ) Tj (write) Tj (\() Tj .729412 .129412 .129412 rg ("data1") Tj 0 0 0 rg (\)) Tj T* .4 .4 .4 rg (<) Tj 0 0 0 rg (Thread) Tj (\() Tj (write) Tj .4 .4 .4 rg (-) Tj (1) Tj 0 0 0 rg (,) Tj ( ) Tj (started) Tj .4 .4 .4 rg (...) Tj 0 0 0 rg (\)) Tj .4 .4 .4 rg (>) Tj 0 0 0 rg T* T* .4 .4 .4 rg (>) Tj (>) Tj (>) Tj 0 0 0 rg ( ) Tj (time) Tj .4 .4 .4 rg (.) Tj 0 0 0 rg (sleep) Tj (\() Tj .4 .4 .4 rg (.) Tj (1) Tj 0 0 0 rg (\)) Tj ( ) Tj /F7 10 Tf .25098 .501961 .501961 rg (# wait a bit, so we are sure data2 is written after data1) Tj /F5 10 Tf 0 0 0 rg T* T* .4 .4 .4 rg (>) Tj (>) Tj (>) Tj 0 0 0 rg ( ) Tj (write) Tj (\() Tj .729412 .129412 .129412 rg ("data2") Tj 0 0 0 rg (\)) Tj T* .4 .4 .4 rg (<) Tj 0 0 0 rg (Thread) Tj (\() Tj (write) Tj .4 .4 .4 rg (-) Tj (2) Tj 0 0 0 rg (,) Tj ( ) Tj (started) Tj .4 .4 .4 rg (...) Tj 0 0 0 rg (\)) Tj .4 .4 .4 rg (>) Tj 0 0 0 rg T* T* .4 .4 .4 rg (>) Tj (>) Tj (>) Tj 0 0 0 rg ( ) Tj (time) Tj .4 .4 .4 rg (.) Tj 0 0 0 rg (sleep) Tj (\() Tj .4 .4 .4 rg (2) Tj 0 0 0 rg (\)) Tj ( ) Tj /F7 10 Tf .25098 .501961 .501961 rg (# wait for the writers to complete) Tj /F5 10 Tf 0 0 0 rg T* T* .4 .4 .4 rg (>) Tj (>) Tj (>) Tj 0 0 0 rg ( ) Tj /F3 10 Tf 0 .501961 0 rg (print) Tj /F5 10 Tf 0 0 0 rg ( ) Tj (datalist) Tj T* ([) Tj .729412 .129412 .129412 rg ('data1') Tj 0 0 0 rg (,) Tj ( ) Tj .729412 .129412 .129412 rg ('data2') Tj 0 0 0 rg (]) Tj T* ET +Q +Q +Q +Q +Q +q +1 0 0 1 62.69291 222.4236 cm +q +BT 1 0 0 1 0 8.435 Tm 21 TL /F2 17.5 Tf 0 0 0 rg (The ) Tj /F3 17.5 Tf (FunctionMaker ) Tj /F2 17.5 Tf (class) Tj T* ET +Q +Q +q +1 0 0 1 62.69291 156.4236 cm +q +BT 1 0 0 1 0 52.82 Tm 2.241412 Tw 12 TL /F1 10 Tf 0 0 0 rg (You may wonder about how the functionality of the ) Tj /F5 10 Tf (decorator ) Tj /F1 10 Tf (module is implemented. The basic) Tj T* 0 Tw 1.545868 Tw (building block is a ) Tj /F5 10 Tf (FunctionMaker ) Tj /F1 10 Tf (class which is able to generate on the fly functions with a given) Tj T* 0 Tw .047485 Tw (name and signature from a function template passed as a string. Generally speaking, you should not need) Tj T* 0 Tw 1.164983 Tw (to resort to ) Tj /F5 10 Tf (FunctionMaker ) Tj /F1 10 Tf (when writing ordinary decorators, but it is handy in some circumstances.) Tj T* 0 Tw (You will see an example shortly, in the implementation of a cool decorator utility \() Tj /F5 10 Tf (decorator_apply) Tj /F1 10 Tf (\).) Tj T* ET +Q +Q +q +1 0 0 1 62.69291 114.4236 cm +q +BT 1 0 0 1 0 28.82 Tm .414597 Tw 12 TL /F5 10 Tf 0 0 0 rg (FunctionMaker ) Tj /F1 10 Tf (provides a ) Tj /F5 10 Tf (.create ) Tj /F1 10 Tf (classmethod which takes as input the name, signature, and body) Tj T* 0 Tw .632927 Tw (of the function we want to generate as well as the execution environment were the function is generated) Tj T* 0 Tw (by ) Tj /F5 10 Tf (exec) Tj /F1 10 Tf (. Here is an example:) Tj T* ET +Q +Q + +endstream + +endobj +% 'R90': class PDFStream +90 0 obj +% page stream +<< /Length 8188 >> +stream +1 0 0 1 0 0 cm BT /F1 12 Tf 14.4 TL ET +q +1 0 0 1 62.69291 679.8236 cm +q +q +1 0 0 1 0 0 cm +q +1 0 0 1 6.6 6.6 cm +q +.662745 .662745 .662745 RG +.5 w +.960784 .960784 .862745 rg +n -6 -6 468.6898 84 re B* +Q +q +BT 1 0 0 1 0 65.71 Tm 12 TL /F5 10 Tf .4 .4 .4 rg (>) Tj (>) Tj (>) Tj 0 0 0 rg ( ) Tj /F3 10 Tf 0 .501961 0 rg (def) Tj /F5 10 Tf 0 0 0 rg ( ) Tj 0 0 1 rg (f) Tj 0 0 0 rg (\() Tj .4 .4 .4 rg (*) Tj 0 0 0 rg (args) Tj (,) Tj ( ) Tj .4 .4 .4 rg (**) Tj 0 0 0 rg (kw) Tj (\):) Tj ( ) Tj /F7 10 Tf .25098 .501961 .501961 rg (# a function with a generic signature) Tj /F5 10 Tf 0 0 0 rg T* .4 .4 .4 rg (...) Tj 0 0 0 rg ( ) Tj /F3 10 Tf 0 .501961 0 rg (print) Tj /F5 10 Tf 0 0 0 rg ( ) Tj (args) Tj (,) Tj ( ) Tj (kw) Tj T* T* .4 .4 .4 rg (>) Tj (>) Tj (>) Tj 0 0 0 rg ( ) Tj (f1) Tj ( ) Tj .4 .4 .4 rg (=) Tj 0 0 0 rg ( ) Tj (FunctionMaker) Tj .4 .4 .4 rg (.) Tj 0 0 0 rg (create) Tj (\() Tj .729412 .129412 .129412 rg ('f1\(a, b\)') Tj 0 0 0 rg (,) Tj ( ) Tj .729412 .129412 .129412 rg ('f\(a, b\)') Tj 0 0 0 rg (,) Tj ( ) Tj 0 .501961 0 rg (dict) Tj 0 0 0 rg (\() Tj (f) Tj .4 .4 .4 rg (=) Tj 0 0 0 rg (f) Tj (\)\)) Tj T* .4 .4 .4 rg (>) Tj (>) Tj (>) Tj 0 0 0 rg ( ) Tj (f1) Tj (\() Tj .4 .4 .4 rg (1) Tj 0 0 0 rg (,) Tj .4 .4 .4 rg (2) Tj 0 0 0 rg (\)) Tj T* (\() Tj .4 .4 .4 rg (1) Tj 0 0 0 rg (,) Tj ( ) Tj .4 .4 .4 rg (2) Tj 0 0 0 rg (\)) Tj ( ) Tj ({}) Tj T* ET +Q +Q +Q +Q +Q +q +1 0 0 1 62.69291 647.8236 cm +q +BT 1 0 0 1 0 16.82 Tm .226654 Tw 12 TL /F1 10 Tf 0 0 0 rg (It is important to notice that the function body is interpolated before being executed, so be careful with the) Tj T* 0 Tw /F5 10 Tf (% ) Tj /F1 10 Tf (sign!) Tj T* ET +Q +Q +q +1 0 0 1 62.69291 605.8236 cm +q +BT 1 0 0 1 0 28.82 Tm 1.995433 Tw 12 TL /F5 10 Tf 0 0 0 rg (FunctionMaker.create ) Tj /F1 10 Tf (also accepts keyword arguments and such arguments are attached to the) Tj T* 0 Tw 1.64686 Tw (resulting function. This is useful if you want to set some function attributes, for instance the docstring) Tj T* 0 Tw /F5 10 Tf (__doc__) Tj /F1 10 Tf (.) Tj T* ET +Q +Q +q +1 0 0 1 62.69291 563.8236 cm +q +BT 1 0 0 1 0 28.82 Tm .605318 Tw 12 TL /F1 10 Tf 0 0 0 rg (For debugging/introspection purposes it may be useful to see the source code of the generated function;) Tj T* 0 Tw 2.246235 Tw (to do that, just pass the flag ) Tj /F5 10 Tf (addsource=True ) Tj /F1 10 Tf (and a ) Tj /F5 10 Tf (__source__ ) Tj /F1 10 Tf (attribute will be added to the) Tj T* 0 Tw (generated function:) Tj T* ET +Q +Q +q +1 0 0 1 62.69291 470.6236 cm +q +q +1 0 0 1 0 0 cm +q +1 0 0 1 6.6 6.6 cm +q +.662745 .662745 .662745 RG +.5 w +.960784 .960784 .862745 rg +n -6 -6 468.6898 84 re B* +Q +q +BT 1 0 0 1 0 65.71 Tm 12 TL /F5 10 Tf .4 .4 .4 rg (>) Tj (>) Tj (>) Tj 0 0 0 rg ( ) Tj (f1) Tj ( ) Tj .4 .4 .4 rg (=) Tj 0 0 0 rg ( ) Tj (FunctionMaker) Tj .4 .4 .4 rg (.) Tj 0 0 0 rg (create) Tj (\() Tj T* .4 .4 .4 rg (...) Tj 0 0 0 rg ( ) Tj .729412 .129412 .129412 rg ('f1\(a, b\)') Tj 0 0 0 rg (,) Tj ( ) Tj .729412 .129412 .129412 rg ('f\(a, b\)') Tj 0 0 0 rg (,) Tj ( ) Tj 0 .501961 0 rg (dict) Tj 0 0 0 rg (\() Tj (f) Tj .4 .4 .4 rg (=) Tj 0 0 0 rg (f) Tj (\),) Tj ( ) Tj (addsource) Tj .4 .4 .4 rg (=) Tj 0 .501961 0 rg (True) Tj 0 0 0 rg (\)) Tj T* .4 .4 .4 rg (>) Tj (>) Tj (>) Tj 0 0 0 rg ( ) Tj /F3 10 Tf 0 .501961 0 rg (print) Tj /F5 10 Tf 0 0 0 rg ( ) Tj (f1) Tj .4 .4 .4 rg (.) Tj 0 0 0 rg (__source__) Tj T* /F3 10 Tf 0 .501961 0 rg (def) Tj /F5 10 Tf 0 0 0 rg ( ) Tj 0 0 1 rg (f1) Tj 0 0 0 rg (\() Tj (a) Tj (,) Tj ( ) Tj (b) Tj (\):) Tj T* ( ) Tj (f) Tj (\() Tj (a) Tj (,) Tj ( ) Tj (b) Tj (\)) Tj T* .4 .4 .4 rg (<) Tj 0 0 0 rg (BLANKLINE) Tj .4 .4 .4 rg (>) Tj T* ET +Q +Q +Q +Q +Q +q +1 0 0 1 62.69291 330.6236 cm +q +BT 1 0 0 1 0 124.82 Tm .870651 Tw 12 TL /F5 10 Tf 0 0 0 rg (FunctionMaker.create ) Tj /F1 10 Tf (can take as first argument a string, as in the examples before, or a function.) Tj T* 0 Tw .224985 Tw (This is the most common usage, since typically you want to decorate a pre-existing function. A framework) Tj T* 0 Tw 1.606136 Tw (author may want to use directly ) Tj /F5 10 Tf (FunctionMaker.create ) Tj /F1 10 Tf (instead of ) Tj /F5 10 Tf (decorator) Tj /F1 10 Tf (, since it gives you) Tj T* 0 Tw 1.36686 Tw (direct access to the body of the generated function. For instance, suppose you want to instrument the) Tj T* 0 Tw .372209 Tw /F5 10 Tf (__init__ ) Tj /F1 10 Tf (methods of a set of classes, by preserving their signature \(such use case is not made up; this) Tj T* 0 Tw .673828 Tw (is done in SQAlchemy and in other frameworks\). When the first argument of ) Tj /F5 10 Tf (FunctionMaker.create) Tj T* 0 Tw 3.405814 Tw /F1 10 Tf (is a function, a ) Tj /F5 10 Tf (FunctionMaker ) Tj /F1 10 Tf (object is instantiated internally, with attributes ) Tj /F5 10 Tf (args) Tj /F1 10 Tf (, ) Tj /F5 10 Tf (varargs) Tj /F1 10 Tf (,) Tj T* 0 Tw 5.509982 Tw /F5 10 Tf (keywords ) Tj /F1 10 Tf (and ) Tj /F5 10 Tf (defaults ) Tj /F1 10 Tf (which are the the return values of the standard library function) Tj T* 0 Tw .561318 Tw /F5 10 Tf (inspect.getargspec) Tj /F1 10 Tf (. For each argument in the ) Tj /F5 10 Tf (args ) Tj /F1 10 Tf (\(which is a list of strings containing the names) Tj T* 0 Tw 1.599985 Tw (of the mandatory arguments\) an attribute ) Tj /F5 10 Tf (arg0) Tj /F1 10 Tf (, ) Tj /F5 10 Tf (arg1) Tj /F1 10 Tf (, ..., ) Tj /F5 10 Tf (argN ) Tj /F1 10 Tf (is also generated. Finally, there is a) Tj T* 0 Tw /F5 10 Tf (signature ) Tj /F1 10 Tf (attribute, a string with the signature of the original function.) Tj T* ET +Q +Q +q +1 0 0 1 62.69291 252.6236 cm +q +BT 1 0 0 1 0 64.82 Tm 4.63311 Tw 12 TL /F1 10 Tf 0 0 0 rg (Notice that while I do not have plans to change or remove the functionality provided in the) Tj T* 0 Tw 1.00936 Tw /F5 10 Tf (FunctionMaker ) Tj /F1 10 Tf (class, I do not guarantee that it will stay unchanged forever. For instance, right now I) Tj T* 0 Tw .791318 Tw (am using the traditional string interpolation syntax for function templates, but Python 2.6 and Python 3.0) Tj T* 0 Tw .712093 Tw (provide a newer interpolation syntax and I may use the new syntax in the future. On the other hand, the) Tj T* 0 Tw .639985 Tw (functionality provided by ) Tj /F5 10 Tf (decorator ) Tj /F1 10 Tf (has been there from version 0.1 and it is guaranteed to stay there) Tj T* 0 Tw (forever.) Tj T* ET +Q +Q +q +1 0 0 1 62.69291 219.6236 cm +q +BT 1 0 0 1 0 8.435 Tm 21 TL /F2 17.5 Tf 0 0 0 rg (Getting the source code) Tj T* ET +Q +Q +q +1 0 0 1 62.69291 141.6236 cm +q +BT 1 0 0 1 0 64.82 Tm 5.045529 Tw 12 TL /F1 10 Tf 0 0 0 rg (Internally ) Tj /F5 10 Tf (FunctionMaker.create ) Tj /F1 10 Tf (uses ) Tj /F5 10 Tf (exec ) Tj /F1 10 Tf (to generate the decorated function. Therefore) Tj T* 0 Tw 2.542126 Tw /F5 10 Tf (inspect.getsource ) Tj /F1 10 Tf (will not work for decorated functions. That means that the usual '??' trick in) Tj T* 0 Tw 2.163059 Tw (IPython will give you the \(right on the spot\) message ) Tj /F5 10 Tf (Dynamically generated function. No) Tj T* 0 Tw .563314 Tw (source code available) Tj /F1 10 Tf (. In the past I have considered this acceptable, since ) Tj /F5 10 Tf (inspect.getsource) Tj T* 0 Tw 1.790697 Tw /F1 10 Tf (does not really work even with regular decorators. In that case ) Tj /F5 10 Tf (inspect.getsource ) Tj /F1 10 Tf (gives you the) Tj T* 0 Tw (wrapper source code which is probably not what you want:) Tj T* ET +Q +Q +q +1 0 0 1 62.69291 84.42362 cm +q +q +1 0 0 1 0 0 cm +q +1 0 0 1 6.6 6.6 cm +q +.662745 .662745 .662745 RG +.5 w +.960784 .960784 .862745 rg +n -6 -6 468.6898 48 re B* +Q +q +BT 1 0 0 1 0 29.71 Tm 12 TL /F3 10 Tf 0 .501961 0 rg (def) Tj /F5 10 Tf 0 0 0 rg ( ) Tj 0 0 1 rg (identity_dec) Tj 0 0 0 rg (\() Tj (func) Tj (\):) Tj T* ( ) Tj /F3 10 Tf 0 .501961 0 rg (def) Tj /F5 10 Tf 0 0 0 rg ( ) Tj 0 0 1 rg (wrapper) Tj 0 0 0 rg (\() Tj .4 .4 .4 rg (*) Tj 0 0 0 rg (args) Tj (,) Tj ( ) Tj .4 .4 .4 rg (**) Tj 0 0 0 rg (kw) Tj (\):) Tj T* ( ) Tj /F3 10 Tf 0 .501961 0 rg (return) Tj /F5 10 Tf 0 0 0 rg ( ) Tj (func) Tj (\() Tj .4 .4 .4 rg (*) Tj 0 0 0 rg (args) Tj (,) Tj ( ) Tj .4 .4 .4 rg (**) Tj 0 0 0 rg (kw) Tj (\)) Tj T* ET +Q +Q +Q +Q +Q + +endstream + +endobj +% 'R91': class PDFStream +91 0 obj +% page stream +<< /Length 7306 >> +stream +1 0 0 1 0 0 cm BT /F1 12 Tf 14.4 TL ET +q +1 0 0 1 62.69291 739.8236 cm +q +q +1 0 0 1 0 0 cm +q +1 0 0 1 6.6 6.6 cm +q +.662745 .662745 .662745 RG +.5 w +.960784 .960784 .862745 rg +n -6 -6 468.6898 24 re B* +Q +q +BT 1 0 0 1 0 5.71 Tm 12 TL /F5 10 Tf 0 0 0 rg ( ) Tj /F3 10 Tf 0 .501961 0 rg (return) Tj /F5 10 Tf 0 0 0 rg ( ) Tj (wrapper) Tj T* ET +Q +Q +Q +Q +Q +q +1 0 0 1 62.69291 634.6236 cm +q +q +1 0 0 1 0 0 cm +q +1 0 0 1 6.6 6.6 cm +q +.662745 .662745 .662745 RG +.5 w +.960784 .960784 .862745 rg +n -6 -6 468.6898 96 re B* +Q +q +BT 1 0 0 1 0 77.71 Tm 12 TL /F5 10 Tf .666667 .133333 1 rg (@identity_dec) Tj 0 0 0 rg T* /F3 10 Tf 0 .501961 0 rg (def) Tj /F5 10 Tf 0 0 0 rg ( ) Tj 0 0 1 rg (example) Tj 0 0 0 rg (\(\):) Tj ( ) Tj /F3 10 Tf 0 .501961 0 rg (pass) Tj /F5 10 Tf 0 0 0 rg T* T* .4 .4 .4 rg (>) Tj (>) Tj (>) Tj 0 0 0 rg ( ) Tj /F3 10 Tf 0 .501961 0 rg (print) Tj /F5 10 Tf 0 0 0 rg ( ) Tj (inspect) Tj .4 .4 .4 rg (.) Tj 0 0 0 rg (getsource) Tj (\() Tj (example) Tj (\)) Tj T* ( ) Tj /F3 10 Tf 0 .501961 0 rg (def) Tj /F5 10 Tf 0 0 0 rg ( ) Tj 0 0 1 rg (wrapper) Tj 0 0 0 rg (\() Tj .4 .4 .4 rg (*) Tj 0 0 0 rg (args) Tj (,) Tj ( ) Tj .4 .4 .4 rg (**) Tj 0 0 0 rg (kw) Tj (\):) Tj T* ( ) Tj /F3 10 Tf 0 .501961 0 rg (return) Tj /F5 10 Tf 0 0 0 rg ( ) Tj (func) Tj (\() Tj .4 .4 .4 rg (*) Tj 0 0 0 rg (args) Tj (,) Tj ( ) Tj .4 .4 .4 rg (**) Tj 0 0 0 rg (kw) Tj (\)) Tj T* .4 .4 .4 rg (<) Tj 0 0 0 rg (BLANKLINE) Tj .4 .4 .4 rg (>) Tj T* ET +Q +Q +Q +Q +Q +q +1 0 0 1 62.69291 578.6236 cm +q +BT 1 0 0 1 0 40.82 Tm 1.471235 Tw 12 TL /F1 10 Tf 0 0 0 rg (\(see bug report ) Tj 0 0 .501961 rg (1764286 ) Tj 0 0 0 rg (for an explanation of what is happening\). Unfortunately the bug is still there,) Tj T* 0 Tw 1.541235 Tw (even in Python 2.6 and 3.0. There is however a workaround. The decorator module adds an attribute) Tj T* 0 Tw .103984 Tw /F5 10 Tf (.undecorated ) Tj /F1 10 Tf (to the decorated function, containing a reference to the original function. The easy way to) Tj T* 0 Tw (get the source code is to call ) Tj /F5 10 Tf (inspect.getsource ) Tj /F1 10 Tf (on the undecorated function:) Tj T* ET +Q +Q +q +1 0 0 1 62.69291 473.4236 cm +q +q +1 0 0 1 0 0 cm +q +1 0 0 1 6.6 6.6 cm +q +.662745 .662745 .662745 RG +.5 w +.960784 .960784 .862745 rg +n -6 -6 468.6898 96 re B* +Q +q +BT 1 0 0 1 0 77.71 Tm 12 TL /F5 10 Tf .4 .4 .4 rg (>) Tj (>) Tj (>) Tj 0 0 0 rg ( ) Tj /F3 10 Tf 0 .501961 0 rg (print) Tj /F5 10 Tf 0 0 0 rg ( ) Tj (inspect) Tj .4 .4 .4 rg (.) Tj 0 0 0 rg (getsource) Tj (\() Tj (factorial) Tj .4 .4 .4 rg (.) Tj 0 0 0 rg (undecorated) Tj (\)) Tj T* .666667 .133333 1 rg (@tail_recursive) Tj 0 0 0 rg T* /F3 10 Tf 0 .501961 0 rg (def) Tj /F5 10 Tf 0 0 0 rg ( ) Tj 0 0 1 rg (factorial) Tj 0 0 0 rg (\() Tj (n) Tj (,) Tj ( ) Tj (acc) Tj .4 .4 .4 rg (=) Tj (1) Tj 0 0 0 rg (\):) Tj T* ( ) Tj .729412 .129412 .129412 rg ("The good old factorial") Tj 0 0 0 rg T* ( ) Tj /F3 10 Tf 0 .501961 0 rg (if) Tj /F5 10 Tf 0 0 0 rg ( ) Tj (n) Tj ( ) Tj .4 .4 .4 rg (==) Tj 0 0 0 rg ( ) Tj .4 .4 .4 rg (0) Tj 0 0 0 rg (:) Tj ( ) Tj /F3 10 Tf 0 .501961 0 rg (return) Tj /F5 10 Tf 0 0 0 rg ( ) Tj (acc) Tj T* ( ) Tj /F3 10 Tf 0 .501961 0 rg (return) Tj /F5 10 Tf 0 0 0 rg ( ) Tj (factorial) Tj (\() Tj (n) Tj .4 .4 .4 rg (-) Tj (1) Tj 0 0 0 rg (,) Tj ( ) Tj (n) Tj .4 .4 .4 rg (*) Tj 0 0 0 rg (acc) Tj (\)) Tj T* .4 .4 .4 rg (<) Tj 0 0 0 rg (BLANKLINE) Tj .4 .4 .4 rg (>) Tj T* ET +Q +Q +Q +Q +Q +q +1 0 0 1 62.69291 440.4236 cm +q +BT 1 0 0 1 0 8.435 Tm 21 TL /F2 17.5 Tf 0 0 0 rg (Dealing with third party decorators) Tj T* ET +Q +Q +q +1 0 0 1 62.69291 386.4236 cm +q +BT 1 0 0 1 0 40.82 Tm .321654 Tw 12 TL /F1 10 Tf 0 0 0 rg (Sometimes you find on the net some cool decorator that you would like to include in your code. However,) Tj T* 0 Tw .50061 Tw (more often than not the cool decorator is not signature-preserving. Therefore you may want an easy way) Tj T* 0 Tw 1.814597 Tw (to upgrade third party decorators to signature-preserving decorators without having to rewrite them in) Tj T* 0 Tw (terms of ) Tj /F5 10 Tf (decorator) Tj /F1 10 Tf (. You can use a ) Tj /F5 10 Tf (FunctionMaker ) Tj /F1 10 Tf (to implement that functionality as follows:) Tj T* ET +Q +Q +q +1 0 0 1 62.69291 269.2236 cm +q +q +1 0 0 1 0 0 cm +q +1 0 0 1 6.6 6.6 cm +q +.662745 .662745 .662745 RG +.5 w +.960784 .960784 .862745 rg +n -6 -6 468.6898 108 re B* +Q +q +BT 1 0 0 1 0 89.71 Tm 12 TL /F3 10 Tf 0 .501961 0 rg (def) Tj /F5 10 Tf 0 0 0 rg ( ) Tj 0 0 1 rg (decorator_apply) Tj 0 0 0 rg (\() Tj (dec) Tj (,) Tj ( ) Tj (func) Tj (\):) Tj T* ( ) Tj /F7 10 Tf .729412 .129412 .129412 rg (""") Tj T* ( Decorate a function by preserving the signature even if dec) Tj T* ( is not a signature-preserving decorator.) Tj T* ( """) Tj /F5 10 Tf 0 0 0 rg T* ( ) Tj /F3 10 Tf 0 .501961 0 rg (return) Tj /F5 10 Tf 0 0 0 rg ( ) Tj (FunctionMaker) Tj .4 .4 .4 rg (.) Tj 0 0 0 rg (create) Tj (\() Tj T* ( ) Tj (func) Tj (,) Tj ( ) Tj .729412 .129412 .129412 rg ('return decorated\() Tj /F3 10 Tf .733333 .4 .533333 rg (%\(signature\)s) Tj /F5 10 Tf .729412 .129412 .129412 rg (\)') Tj 0 0 0 rg (,) Tj T* ( ) Tj 0 .501961 0 rg (dict) Tj 0 0 0 rg (\() Tj (decorated) Tj .4 .4 .4 rg (=) Tj 0 0 0 rg (dec) Tj (\() Tj (func) Tj (\)\),) Tj ( ) Tj (undecorated) Tj .4 .4 .4 rg (=) Tj 0 0 0 rg (func) Tj (\)) Tj T* ET +Q +Q +Q +Q +Q +q +1 0 0 1 62.69291 237.2236 cm +q +BT 1 0 0 1 0 16.82 Tm .698314 Tw 12 TL /F5 10 Tf 0 0 0 rg (decorator_apply ) Tj /F1 10 Tf (sets the attribute ) Tj /F5 10 Tf (.undecorated ) Tj /F1 10 Tf (of the generated function to the original function,) Tj T* 0 Tw (so that you can get the right source code.) Tj T* ET +Q +Q +q +1 0 0 1 62.69291 195.2236 cm +q +BT 1 0 0 1 0 28.82 Tm .13104 Tw 12 TL /F1 10 Tf 0 0 0 rg (Notice that I am not providing this functionality in the ) Tj /F5 10 Tf (decorator ) Tj /F1 10 Tf (module directly since I think it is best to) Tj T* 0 Tw 2.070751 Tw (rewrite the decorator rather than adding an additional level of indirection. However, practicality beats) Tj T* 0 Tw (purity, so you can add ) Tj /F5 10 Tf (decorator_apply ) Tj /F1 10 Tf (to your toolbox and use it if you need to.) Tj T* ET +Q +Q +q +1 0 0 1 62.69291 141.2236 cm +q +BT 1 0 0 1 0 40.82 Tm 1.74881 Tw 12 TL /F1 10 Tf 0 0 0 rg (In order to give an example of usage of ) Tj /F5 10 Tf (decorator_apply) Tj /F1 10 Tf (, I will show a pretty slick decorator that) Tj T* 0 Tw 1.276651 Tw (converts a tail-recursive function in an iterative function. I have shamelessly stolen the basic idea from) Tj T* 0 Tw 43.62829 Tw (Kay Schluehr's recipe in the Python Cookbook,) Tj T* 0 Tw 0 0 .501961 rg (http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/496691) Tj 0 0 0 rg (.) Tj T* ET +Q +Q +q +1 0 0 1 62.69291 84.02362 cm +q +q +1 0 0 1 0 0 cm +q +1 0 0 1 6.6 6.6 cm +q +.662745 .662745 .662745 RG +.5 w +.960784 .960784 .862745 rg +n -6 -6 468.6898 48 re B* +Q +q +BT 1 0 0 1 0 29.71 Tm 12 TL /F3 10 Tf 0 .501961 0 rg (class) Tj /F5 10 Tf 0 0 0 rg ( ) Tj /F3 10 Tf 0 0 1 rg (TailRecursive) Tj /F5 10 Tf 0 0 0 rg (\() Tj 0 .501961 0 rg (object) Tj 0 0 0 rg (\):) Tj T* ( ) Tj /F7 10 Tf .729412 .129412 .129412 rg (""") Tj T* ( tail_recursive decorator based on Kay Schluehr's recipe) Tj T* ET +Q +Q +Q +Q +Q + +endstream + +endobj +% 'R92': class PDFStream +92 0 obj +% page stream +<< /Length 7889 >> +stream +1 0 0 1 0 0 cm BT /F1 12 Tf 14.4 TL ET +q +1 0 0 1 62.69291 439.8236 cm +q +q +1 0 0 1 0 0 cm +q +1 0 0 1 6.6 6.6 cm +q +.662745 .662745 .662745 RG +.5 w +.960784 .960784 .862745 rg +n -6 -6 468.6898 324 re B* +Q +q +BT 1 0 0 1 0 305.71 Tm 12 TL /F7 10 Tf .729412 .129412 .129412 rg ( http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/496691) Tj T* ( with improvements by me and George Sakkis.) Tj T* ( """) Tj /F5 10 Tf 0 0 0 rg T* T* ( ) Tj /F3 10 Tf 0 .501961 0 rg (def) Tj /F5 10 Tf 0 0 0 rg ( ) Tj 0 0 1 rg (__init__) Tj 0 0 0 rg (\() Tj 0 .501961 0 rg (self) Tj 0 0 0 rg (,) Tj ( ) Tj (func) Tj (\):) Tj T* ( ) Tj 0 .501961 0 rg (self) Tj .4 .4 .4 rg (.) Tj 0 0 0 rg (func) Tj ( ) Tj .4 .4 .4 rg (=) Tj 0 0 0 rg ( ) Tj (func) Tj T* ( ) Tj 0 .501961 0 rg (self) Tj .4 .4 .4 rg (.) Tj 0 0 0 rg (firstcall) Tj ( ) Tj .4 .4 .4 rg (=) Tj 0 0 0 rg ( ) Tj 0 .501961 0 rg (True) Tj 0 0 0 rg T* ( ) Tj 0 .501961 0 rg (self) Tj .4 .4 .4 rg (.) Tj 0 0 0 rg (CONTINUE) Tj ( ) Tj .4 .4 .4 rg (=) Tj 0 0 0 rg ( ) Tj 0 .501961 0 rg (object) Tj 0 0 0 rg (\(\)) Tj ( ) Tj /F7 10 Tf .25098 .501961 .501961 rg (# sentinel) Tj /F5 10 Tf 0 0 0 rg T* T* ( ) Tj /F3 10 Tf 0 .501961 0 rg (def) Tj /F5 10 Tf 0 0 0 rg ( ) Tj 0 0 1 rg (__call__) Tj 0 0 0 rg (\() Tj 0 .501961 0 rg (self) Tj 0 0 0 rg (,) Tj ( ) Tj .4 .4 .4 rg (*) Tj 0 0 0 rg (args) Tj (,) Tj ( ) Tj .4 .4 .4 rg (**) Tj 0 0 0 rg (kwd) Tj (\):) Tj T* ( ) Tj (CONTINUE) Tj ( ) Tj .4 .4 .4 rg (=) Tj 0 0 0 rg ( ) Tj 0 .501961 0 rg (self) Tj .4 .4 .4 rg (.) Tj 0 0 0 rg (CONTINUE) Tj T* ( ) Tj /F3 10 Tf 0 .501961 0 rg (if) Tj /F5 10 Tf 0 0 0 rg ( ) Tj 0 .501961 0 rg (self) Tj .4 .4 .4 rg (.) Tj 0 0 0 rg (firstcall) Tj (:) Tj T* ( ) Tj (func) Tj ( ) Tj .4 .4 .4 rg (=) Tj 0 0 0 rg ( ) Tj 0 .501961 0 rg (self) Tj .4 .4 .4 rg (.) Tj 0 0 0 rg (func) Tj T* ( ) Tj 0 .501961 0 rg (self) Tj .4 .4 .4 rg (.) Tj 0 0 0 rg (firstcall) Tj ( ) Tj .4 .4 .4 rg (=) Tj 0 0 0 rg ( ) Tj 0 .501961 0 rg (False) Tj 0 0 0 rg T* ( ) Tj /F3 10 Tf 0 .501961 0 rg (try) Tj /F5 10 Tf 0 0 0 rg (:) Tj T* ( ) Tj /F3 10 Tf 0 .501961 0 rg (while) Tj /F5 10 Tf 0 0 0 rg ( ) Tj 0 .501961 0 rg (True) Tj 0 0 0 rg (:) Tj T* ( ) Tj (result) Tj ( ) Tj .4 .4 .4 rg (=) Tj 0 0 0 rg ( ) Tj (func) Tj (\() Tj .4 .4 .4 rg (*) Tj 0 0 0 rg (args) Tj (,) Tj ( ) Tj .4 .4 .4 rg (**) Tj 0 0 0 rg (kwd) Tj (\)) Tj T* ( ) Tj /F3 10 Tf 0 .501961 0 rg (if) Tj /F5 10 Tf 0 0 0 rg ( ) Tj (result) Tj ( ) Tj /F3 10 Tf .666667 .133333 1 rg (is) Tj /F5 10 Tf 0 0 0 rg ( ) Tj (CONTINUE) Tj (:) Tj ( ) Tj /F7 10 Tf .25098 .501961 .501961 rg (# update arguments) Tj /F5 10 Tf 0 0 0 rg T* ( ) Tj (args) Tj (,) Tj ( ) Tj (kwd) Tj ( ) Tj .4 .4 .4 rg (=) Tj 0 0 0 rg ( ) Tj 0 .501961 0 rg (self) Tj .4 .4 .4 rg (.) Tj 0 0 0 rg (argskwd) Tj T* ( ) Tj /F3 10 Tf 0 .501961 0 rg (else) Tj /F5 10 Tf 0 0 0 rg (:) Tj ( ) Tj /F7 10 Tf .25098 .501961 .501961 rg (# last call) Tj /F5 10 Tf 0 0 0 rg T* ( ) Tj /F3 10 Tf 0 .501961 0 rg (return) Tj /F5 10 Tf 0 0 0 rg ( ) Tj (result) Tj T* ( ) Tj /F3 10 Tf 0 .501961 0 rg (finally) Tj /F5 10 Tf 0 0 0 rg (:) Tj T* ( ) Tj 0 .501961 0 rg (self) Tj .4 .4 .4 rg (.) Tj 0 0 0 rg (firstcall) Tj ( ) Tj .4 .4 .4 rg (=) Tj 0 0 0 rg ( ) Tj 0 .501961 0 rg (True) Tj 0 0 0 rg T* ( ) Tj /F3 10 Tf 0 .501961 0 rg (else) Tj /F5 10 Tf 0 0 0 rg (:) Tj ( ) Tj /F7 10 Tf .25098 .501961 .501961 rg (# return the arguments of the tail call) Tj /F5 10 Tf 0 0 0 rg T* ( ) Tj 0 .501961 0 rg (self) Tj .4 .4 .4 rg (.) Tj 0 0 0 rg (argskwd) Tj ( ) Tj .4 .4 .4 rg (=) Tj 0 0 0 rg ( ) Tj (args) Tj (,) Tj ( ) Tj (kwd) Tj T* ( ) Tj /F3 10 Tf 0 .501961 0 rg (return) Tj /F5 10 Tf 0 0 0 rg ( ) Tj (CONTINUE) Tj T* ET +Q +Q +Q +Q +Q +q +1 0 0 1 62.69291 419.8236 cm +q +0 0 0 rg +BT 1 0 0 1 0 4.82 Tm /F1 10 Tf 12 TL (Here the decorator is implemented as a class returning callable objects.) Tj T* ET +Q +Q +q +1 0 0 1 62.69291 374.6236 cm +q +q +1 0 0 1 0 0 cm +q +1 0 0 1 6.6 6.6 cm +q +.662745 .662745 .662745 RG +.5 w +.960784 .960784 .862745 rg +n -6 -6 468.6898 36 re B* +Q +q +BT 1 0 0 1 0 17.71 Tm 12 TL /F3 10 Tf 0 .501961 0 rg (def) Tj /F5 10 Tf 0 0 0 rg ( ) Tj 0 0 1 rg (tail_recursive) Tj 0 0 0 rg (\() Tj (func) Tj (\):) Tj T* ( ) Tj /F3 10 Tf 0 .501961 0 rg (return) Tj /F5 10 Tf 0 0 0 rg ( ) Tj (decorator_apply) Tj (\() Tj (TailRecursive) Tj (,) Tj ( ) Tj (func) Tj (\)) Tj T* ET +Q +Q +Q +Q +Q +q +1 0 0 1 62.69291 354.6236 cm +q +0 0 0 rg +BT 1 0 0 1 0 4.82 Tm /F1 10 Tf 12 TL (Here is how you apply the upgraded decorator to the good old factorial:) Tj T* ET +Q +Q +q +1 0 0 1 62.69291 273.4236 cm +q +q +1 0 0 1 0 0 cm +q +1 0 0 1 6.6 6.6 cm +q +.662745 .662745 .662745 RG +.5 w +.960784 .960784 .862745 rg +n -6 -6 468.6898 72 re B* +Q +q +BT 1 0 0 1 0 53.71 Tm 12 TL /F5 10 Tf .666667 .133333 1 rg (@tail_recursive) Tj 0 0 0 rg T* /F3 10 Tf 0 .501961 0 rg (def) Tj /F5 10 Tf 0 0 0 rg ( ) Tj 0 0 1 rg (factorial) Tj 0 0 0 rg (\() Tj (n) Tj (,) Tj ( ) Tj (acc) Tj .4 .4 .4 rg (=) Tj (1) Tj 0 0 0 rg (\):) Tj T* ( ) Tj .729412 .129412 .129412 rg ("The good old factorial") Tj 0 0 0 rg T* ( ) Tj /F3 10 Tf 0 .501961 0 rg (if) Tj /F5 10 Tf 0 0 0 rg ( ) Tj (n) Tj ( ) Tj .4 .4 .4 rg (==) Tj 0 0 0 rg ( ) Tj .4 .4 .4 rg (0) Tj 0 0 0 rg (:) Tj ( ) Tj /F3 10 Tf 0 .501961 0 rg (return) Tj /F5 10 Tf 0 0 0 rg ( ) Tj (acc) Tj T* ( ) Tj /F3 10 Tf 0 .501961 0 rg (return) Tj /F5 10 Tf 0 0 0 rg ( ) Tj (factorial) Tj (\() Tj (n) Tj .4 .4 .4 rg (-) Tj (1) Tj 0 0 0 rg (,) Tj ( ) Tj (n) Tj .4 .4 .4 rg (*) Tj 0 0 0 rg (acc) Tj (\)) Tj T* ET +Q +Q +Q +Q +Q +q +1 0 0 1 62.69291 228.2236 cm +q +q +1 0 0 1 0 0 cm +q +1 0 0 1 6.6 6.6 cm +q +.662745 .662745 .662745 RG +.5 w +.960784 .960784 .862745 rg +n -6 -6 468.6898 36 re B* +Q +q +BT 1 0 0 1 0 17.71 Tm 12 TL /F5 10 Tf .4 .4 .4 rg (>) Tj (>) Tj (>) Tj 0 0 0 rg ( ) Tj /F3 10 Tf 0 .501961 0 rg (print) Tj /F5 10 Tf 0 0 0 rg ( ) Tj (factorial) Tj (\() Tj .4 .4 .4 rg (4) Tj 0 0 0 rg (\)) Tj T* .4 .4 .4 rg (24) Tj T* ET +Q +Q +Q +Q +Q +q +1 0 0 1 62.69291 172.2236 cm +q +BT 1 0 0 1 0 40.82 Tm .188935 Tw 12 TL /F1 10 Tf 0 0 0 rg (This decorator is pretty impressive, and should give you some food for your mind ;\) Notice that there is no) Tj T* 0 Tw 1.339983 Tw (recursion limit now, and you can easily compute ) Tj /F5 10 Tf (factorial\(1001\) ) Tj /F1 10 Tf (or larger without filling the stack) Tj T* 0 Tw .909431 Tw (frame. Notice also that the decorator will not work on functions which are not tail recursive, such as the) Tj T* 0 Tw (following) Tj T* ET +Q +Q +q +1 0 0 1 62.69291 115.0236 cm +q +q +1 0 0 1 0 0 cm +q +1 0 0 1 6.6 6.6 cm +q +.662745 .662745 .662745 RG +.5 w +.960784 .960784 .862745 rg +n -6 -6 468.6898 48 re B* +Q +q +BT 1 0 0 1 0 29.71 Tm 12 TL /F3 10 Tf 0 .501961 0 rg (def) Tj /F5 10 Tf 0 0 0 rg ( ) Tj 0 0 1 rg (fact) Tj 0 0 0 rg (\() Tj (n) Tj (\):) Tj ( ) Tj /F7 10 Tf .25098 .501961 .501961 rg (# this is not tail-recursive) Tj /F5 10 Tf 0 0 0 rg T* ( ) Tj /F3 10 Tf 0 .501961 0 rg (if) Tj /F5 10 Tf 0 0 0 rg ( ) Tj (n) Tj ( ) Tj .4 .4 .4 rg (==) Tj 0 0 0 rg ( ) Tj .4 .4 .4 rg (0) Tj 0 0 0 rg (:) Tj ( ) Tj /F3 10 Tf 0 .501961 0 rg (return) Tj /F5 10 Tf 0 0 0 rg ( ) Tj .4 .4 .4 rg (1) Tj 0 0 0 rg T* ( ) Tj /F3 10 Tf 0 .501961 0 rg (return) Tj /F5 10 Tf 0 0 0 rg ( ) Tj (n) Tj ( ) Tj .4 .4 .4 rg (*) Tj 0 0 0 rg ( ) Tj (fact) Tj (\() Tj (n) Tj .4 .4 .4 rg (-) Tj (1) Tj 0 0 0 rg (\)) Tj T* ET +Q +Q +Q +Q +Q +q +1 0 0 1 62.69291 83.02362 cm +q +0 0 0 rg +BT 1 0 0 1 0 16.82 Tm /F1 10 Tf 12 TL .541098 Tw (\(reminder: a function is tail recursive if it either returns a value without making a recursive call, or returns) Tj T* 0 Tw (directly the result of a recursive call\).) Tj T* ET +Q +Q + +endstream + +endobj +% 'R93': class PDFStream +93 0 obj +% page stream +<< /Length 5004 >> +stream +1 0 0 1 0 0 cm BT /F1 12 Tf 14.4 TL ET +q +1 0 0 1 62.69291 744.0236 cm +q +BT 1 0 0 1 0 8.435 Tm 21 TL /F2 17.5 Tf 0 0 0 rg (Caveats and limitations) Tj T* ET +Q +Q +q +1 0 0 1 62.69291 714.0236 cm +q +0 0 0 rg +BT 1 0 0 1 0 16.82 Tm /F1 10 Tf 12 TL .474987 Tw (The first thing you should be aware of, it the fact that decorators have a performance penalty. The worse) Tj T* 0 Tw (case is shown by the following example:) Tj T* ET +Q +Q +q +1 0 0 1 62.69291 488.8236 cm +q +q +1 0 0 1 0 0 cm +q +1 0 0 1 6.6 6.6 cm +q +.662745 .662745 .662745 RG +.5 w +.960784 .960784 .862745 rg +n -6 -6 468.6898 216 re B* +Q +q +0 0 0 rg +BT 1 0 0 1 0 197.71 Tm /F5 10 Tf 12 TL ($ cat performance.sh) Tj T* (python -m timeit -s ") Tj T* (from decorator import decorator) Tj T* T* (@decorator) Tj T* (def do_nothing\(func, *args, **kw\):) Tj T* ( return func\(*args, **kw\)) Tj T* T* (@do_nothing) Tj T* (def f\(\):) Tj T* ( pass) Tj T* (" "f\(\)") Tj T* T* (python -m timeit -s ") Tj T* (def f\(\):) Tj T* ( pass) Tj T* (" "f\(\)") Tj T* ET +Q +Q +Q +Q +Q +q +1 0 0 1 62.69291 456.8236 cm +q +BT 1 0 0 1 0 16.82 Tm .266235 Tw 12 TL /F1 10 Tf 0 0 0 rg (On my MacBook, using the ) Tj /F5 10 Tf (do_nothing ) Tj /F1 10 Tf (decorator instead of the plain function is more than three times) Tj T* 0 Tw (slower:) Tj T* ET +Q +Q +q +1 0 0 1 62.69291 399.6236 cm +q +q +1 0 0 1 0 0 cm +q +1 0 0 1 6.6 6.6 cm +q +.662745 .662745 .662745 RG +.5 w +.960784 .960784 .862745 rg +n -6 -6 468.6898 48 re B* +Q +q +0 0 0 rg +BT 1 0 0 1 0 29.71 Tm /F5 10 Tf 12 TL ($ bash performance.sh) Tj T* (1000000 loops, best of 3: 0.995 usec per loop) Tj T* (1000000 loops, best of 3: 0.273 usec per loop) Tj T* ET +Q +Q +Q +Q +Q +q +1 0 0 1 62.69291 355.6236 cm +q +BT 1 0 0 1 0 28.82 Tm 1.25832 Tw 12 TL /F1 10 Tf 0 0 0 rg (It should be noted that a real life function would probably do something more useful than ) Tj /F5 10 Tf (f ) Tj /F1 10 Tf (here, and) Tj T* 0 Tw .91811 Tw (therefore in real life the performance penalty could be completely negligible. As always, the only way to) Tj T* 0 Tw (know if there is a penalty in your specific use case is to measure it.) Tj T* ET +Q +Q +q +1 0 0 1 62.69291 325.6236 cm +q +0 0 0 rg +BT 1 0 0 1 0 16.82 Tm /F1 10 Tf 12 TL .867984 Tw (You should be aware that decorators will make your tracebacks longer and more difficult to understand.) Tj T* 0 Tw (Consider this example:) Tj T* ET +Q +Q +q +1 0 0 1 62.69291 268.4236 cm +q +q +1 0 0 1 0 0 cm +q +1 0 0 1 6.6 6.6 cm +q +.662745 .662745 .662745 RG +.5 w +.960784 .960784 .862745 rg +n -6 -6 468.6898 48 re B* +Q +q +BT 1 0 0 1 0 29.71 Tm 12 TL /F5 10 Tf .4 .4 .4 rg (>) Tj (>) Tj (>) Tj 0 0 0 rg ( ) Tj .666667 .133333 1 rg (@trace) Tj 0 0 0 rg T* .4 .4 .4 rg (...) Tj 0 0 0 rg ( ) Tj /F3 10 Tf 0 .501961 0 rg (def) Tj /F5 10 Tf 0 0 0 rg ( ) Tj 0 0 1 rg (f) Tj 0 0 0 rg (\(\):) Tj T* .4 .4 .4 rg (...) Tj 0 0 0 rg ( ) Tj .4 .4 .4 rg (1) Tj (/) Tj (0) Tj T* ET +Q +Q +Q +Q +Q +q +1 0 0 1 62.69291 236.4236 cm +q +BT 1 0 0 1 0 16.82 Tm .583318 Tw 12 TL /F1 10 Tf 0 0 0 rg (Calling ) Tj /F5 10 Tf (f\(\) ) Tj /F1 10 Tf (will give you a ) Tj /F5 10 Tf (ZeroDivisionError) Tj /F1 10 Tf (, but since the function is decorated the traceback will) Tj T* 0 Tw (be longer:) Tj T* ET +Q +Q +q +1 0 0 1 62.69291 107.2236 cm +q +q +1 0 0 1 0 0 cm +q +1 0 0 1 6.6 6.6 cm +q +.662745 .662745 .662745 RG +.5 w +.960784 .960784 .862745 rg +n -6 -6 468.6898 120 re B* +Q +q +BT 1 0 0 1 0 101.71 Tm 12 TL /F5 10 Tf .4 .4 .4 rg (>) Tj (>) Tj (>) Tj 0 0 0 rg ( ) Tj (f) Tj (\(\)) Tj T* (Traceback) Tj ( ) Tj (\() Tj (most) Tj ( ) Tj (recent) Tj ( ) Tj (call) Tj ( ) Tj (last) Tj (\):) Tj T* ( ) Tj .4 .4 .4 rg (...) Tj 0 0 0 rg T* ( ) Tj (File) Tj ( ) Tj .729412 .129412 .129412 rg (") Tj (<) Tj (string) Tj (>) Tj (") Tj 0 0 0 rg (,) Tj ( ) Tj (line) Tj ( ) Tj .4 .4 .4 rg (2) Tj 0 0 0 rg (,) Tj ( ) Tj /F3 10 Tf .666667 .133333 1 rg (in) Tj /F5 10 Tf 0 0 0 rg ( ) Tj (f) Tj T* ( ) Tj (File) Tj ( ) Tj .729412 .129412 .129412 rg (") Tj (<) Tj (doctest __main__[18]) Tj (>) Tj (") Tj 0 0 0 rg (,) Tj ( ) Tj (line) Tj ( ) Tj .4 .4 .4 rg (4) Tj 0 0 0 rg (,) Tj ( ) Tj /F3 10 Tf .666667 .133333 1 rg (in) Tj /F5 10 Tf 0 0 0 rg ( ) Tj (trace) Tj T* ( ) Tj /F3 10 Tf 0 .501961 0 rg (return) Tj /F5 10 Tf 0 0 0 rg ( ) Tj (f) Tj (\() Tj .4 .4 .4 rg (*) Tj 0 0 0 rg (args) Tj (,) Tj ( ) Tj .4 .4 .4 rg (**) Tj 0 0 0 rg (kw) Tj (\)) Tj T* ( ) Tj (File) Tj ( ) Tj .729412 .129412 .129412 rg (") Tj (<) Tj (doctest __main__[47]) Tj (>) Tj (") Tj 0 0 0 rg (,) Tj ( ) Tj (line) Tj ( ) Tj .4 .4 .4 rg (3) Tj 0 0 0 rg (,) Tj ( ) Tj /F3 10 Tf .666667 .133333 1 rg (in) Tj /F5 10 Tf 0 0 0 rg ( ) Tj (f) Tj T* ( ) Tj .4 .4 .4 rg (1) Tj (/) Tj (0) Tj 0 0 0 rg T* /F3 10 Tf .823529 .254902 .227451 rg (ZeroDivisionError) Tj /F5 10 Tf 0 0 0 rg (:) Tj ( ) Tj (integer) Tj ( ) Tj (division) Tj ( ) Tj /F3 10 Tf .666667 .133333 1 rg (or) Tj /F5 10 Tf 0 0 0 rg ( ) Tj (modulo) Tj ( ) Tj (by) Tj ( ) Tj (zero) Tj T* ET +Q +Q +Q +Q +Q + +endstream + +endobj +% 'R94': class PDFStream +94 0 obj +% page stream +<< /Length 7526 >> +stream +1 0 0 1 0 0 cm BT /F1 12 Tf 14.4 TL ET +q +1 0 0 1 62.69291 705.0236 cm +q +BT 1 0 0 1 0 52.82 Tm 1.05528 Tw 12 TL /F1 10 Tf 0 0 0 rg (You see here the inner call to the decorator ) Tj /F5 10 Tf (trace) Tj /F1 10 Tf (, which calls ) Tj /F5 10 Tf (f\(*args, **kw\)) Tj /F1 10 Tf (, and a reference to) Tj T* 0 Tw .265868 Tw /F5 10 Tf (File ") Tj (<) Tj (string) Tj (>) Tj (", line 2, in f) Tj /F1 10 Tf (. This latter reference is due to the fact that internally the decorator) Tj T* 0 Tw 2.053318 Tw (module uses ) Tj /F5 10 Tf (exec ) Tj /F1 10 Tf (to generate the decorated function. Notice that ) Tj /F5 10 Tf (exec ) Tj /F1 10 Tf (is ) Tj /F6 10 Tf (not ) Tj /F1 10 Tf (responsibile for the) Tj T* 0 Tw 1.507485 Tw (performance penalty, since is the called ) Tj /F6 10 Tf (only once ) Tj /F1 10 Tf (at function decoration time, and not every time the) Tj T* 0 Tw (decorated function is called.) Tj T* ET +Q +Q +q +1 0 0 1 62.69291 627.0236 cm +q +BT 1 0 0 1 0 64.82 Tm .932209 Tw 12 TL /F1 10 Tf 0 0 0 rg (At present, there is no clean way to avoid ) Tj /F5 10 Tf (exec) Tj /F1 10 Tf (. A clean solution would require to change the CPython) Tj T* 0 Tw .777485 Tw (implementation of functions and add an hook to make it possible to change their signature directly. That) Tj T* 0 Tw .74186 Tw (could happen in future versions of Python \(see PEP ) Tj 0 0 .501961 rg (362) Tj 0 0 0 rg (\) and then the decorator module would become) Tj T* 0 Tw 2.385318 Tw (obsolete. However, at present, even in Python 3.1 it is impossible to change the function signature) Tj T* 0 Tw .931751 Tw (directly, therefore the ) Tj /F5 10 Tf (decorator ) Tj /F1 10 Tf (module is still useful. Actually, this is one of the main reasons why I) Tj T* 0 Tw (keep maintaining the module and releasing new versions.) Tj T* ET +Q +Q +q +1 0 0 1 62.69291 561.0236 cm +q +BT 1 0 0 1 0 52.82 Tm 1.043828 Tw 12 TL /F1 10 Tf 0 0 0 rg (In the present implementation, decorators generated by ) Tj /F5 10 Tf (decorator ) Tj /F1 10 Tf (can only be used on user-defined) Tj T* 0 Tw .152485 Tw (Python functions or methods, not on generic callable objects, nor on built-in functions, due to limitations of) Tj T* 0 Tw .591235 Tw (the ) Tj /F5 10 Tf (inspect ) Tj /F1 10 Tf (module in the standard library. Moreover, notice that you can decorate a method, but only) Tj T* 0 Tw 2.693516 Tw (before if becomes a bound or unbound method, i.e. inside the class. Here is an example of valid) Tj T* 0 Tw (decoration:) Tj T* ET +Q +Q +q +1 0 0 1 62.69291 491.8236 cm +q +q +1 0 0 1 0 0 cm +q +1 0 0 1 6.6 6.6 cm +q +.662745 .662745 .662745 RG +.5 w +.960784 .960784 .862745 rg +n -6 -6 468.6898 60 re B* +Q +q +BT 1 0 0 1 0 41.71 Tm 12 TL /F5 10 Tf .4 .4 .4 rg (>) Tj (>) Tj (>) Tj 0 0 0 rg ( ) Tj /F3 10 Tf 0 .501961 0 rg (class) Tj /F5 10 Tf 0 0 0 rg ( ) Tj /F3 10 Tf 0 0 1 rg (C) Tj /F5 10 Tf 0 0 0 rg (\() Tj 0 .501961 0 rg (object) Tj 0 0 0 rg (\):) Tj T* .4 .4 .4 rg (...) Tj 0 0 0 rg ( ) Tj .666667 .133333 1 rg (@trace) Tj 0 0 0 rg T* .4 .4 .4 rg (...) Tj 0 0 0 rg ( ) Tj /F3 10 Tf 0 .501961 0 rg (def) Tj /F5 10 Tf 0 0 0 rg ( ) Tj 0 0 1 rg (meth) Tj 0 0 0 rg (\() Tj 0 .501961 0 rg (self) Tj 0 0 0 rg (\):) Tj T* .4 .4 .4 rg (...) Tj 0 0 0 rg ( ) Tj /F3 10 Tf 0 .501961 0 rg (pass) Tj T* ET +Q +Q +Q +Q +Q +q +1 0 0 1 62.69291 471.8236 cm +q +0 0 0 rg +BT 1 0 0 1 0 4.82 Tm /F1 10 Tf 12 TL (Here is an example of invalid decoration, when the decorator in called too late:) Tj T* ET +Q +Q +q +1 0 0 1 62.69291 354.6236 cm +q +q +1 0 0 1 0 0 cm +q +1 0 0 1 6.6 6.6 cm +q +.662745 .662745 .662745 RG +.5 w +.960784 .960784 .862745 rg +n -6 -6 468.6898 108 re B* +Q +q +BT 1 0 0 1 0 89.71 Tm 12 TL /F5 10 Tf .4 .4 .4 rg (>) Tj (>) Tj (>) Tj 0 0 0 rg ( ) Tj /F3 10 Tf 0 .501961 0 rg (class) Tj /F5 10 Tf 0 0 0 rg ( ) Tj /F3 10 Tf 0 0 1 rg (C) Tj /F5 10 Tf 0 0 0 rg (\() Tj 0 .501961 0 rg (object) Tj 0 0 0 rg (\):) Tj T* .4 .4 .4 rg (...) Tj 0 0 0 rg ( ) Tj /F3 10 Tf 0 .501961 0 rg (def) Tj /F5 10 Tf 0 0 0 rg ( ) Tj 0 0 1 rg (meth) Tj 0 0 0 rg (\() Tj 0 .501961 0 rg (self) Tj 0 0 0 rg (\):) Tj T* .4 .4 .4 rg (...) Tj 0 0 0 rg ( ) Tj /F3 10 Tf 0 .501961 0 rg (pass) Tj /F5 10 Tf 0 0 0 rg T* .4 .4 .4 rg (...) Tj 0 0 0 rg T* .4 .4 .4 rg (>) Tj (>) Tj (>) Tj 0 0 0 rg ( ) Tj (trace) Tj (\() Tj (C) Tj .4 .4 .4 rg (.) Tj 0 0 0 rg (meth) Tj (\)) Tj T* (Traceback) Tj ( ) Tj (\() Tj (most) Tj ( ) Tj (recent) Tj ( ) Tj (call) Tj ( ) Tj (last) Tj (\):) Tj T* ( ) Tj .4 .4 .4 rg (...) Tj 0 0 0 rg T* /F3 10 Tf .823529 .254902 .227451 rg (TypeError) Tj /F5 10 Tf 0 0 0 rg (:) Tj ( ) Tj (You) Tj ( ) Tj (are) Tj ( ) Tj (decorating) Tj ( ) Tj (a) Tj ( ) Tj (non) Tj ( ) Tj (function) Tj (:) Tj ( ) Tj .4 .4 .4 rg (<) Tj 0 0 0 rg (unbound) Tj ( ) Tj (method) Tj ( ) Tj (C) Tj .4 .4 .4 rg (.) Tj 0 0 0 rg (meth) Tj .4 .4 .4 rg (>) Tj T* ET +Q +Q +Q +Q +Q +q +1 0 0 1 62.69291 334.6236 cm +q +0 0 0 rg +BT 1 0 0 1 0 4.82 Tm /F1 10 Tf 12 TL (The solution is to extract the inner function from the unbound method:) Tj T* ET +Q +Q +q +1 0 0 1 62.69291 289.4236 cm +q +q +1 0 0 1 0 0 cm +q +1 0 0 1 6.6 6.6 cm +q +.662745 .662745 .662745 RG +.5 w +.960784 .960784 .862745 rg +n -6 -6 468.6898 36 re B* +Q +q +BT 1 0 0 1 0 17.71 Tm 12 TL /F5 10 Tf .4 .4 .4 rg (>) Tj (>) Tj (>) Tj 0 0 0 rg ( ) Tj (trace) Tj (\() Tj (C) Tj .4 .4 .4 rg (.) Tj 0 0 0 rg (meth) Tj .4 .4 .4 rg (.) Tj 0 0 0 rg (im_func) Tj (\)) Tj T* .4 .4 .4 rg (<) Tj 0 0 0 rg (function) Tj ( ) Tj (meth) Tj ( ) Tj (at) Tj ( ) Tj .4 .4 .4 rg (0) Tj 0 0 0 rg (x) Tj .4 .4 .4 rg (...) Tj (>) Tj T* ET +Q +Q +Q +Q +Q +q +1 0 0 1 62.69291 257.4236 cm +q +BT 1 0 0 1 0 16.82 Tm .785777 Tw 12 TL /F1 10 Tf 0 0 0 rg (There is a restriction on the names of the arguments: for instance, if try to call an argument ) Tj /F5 10 Tf (_call_ ) Tj /F1 10 Tf (or) Tj T* 0 Tw /F5 10 Tf (_func_ ) Tj /F1 10 Tf (you will get a ) Tj /F5 10 Tf (NameError) Tj /F1 10 Tf (:) Tj T* ET +Q +Q +q +1 0 0 1 62.69291 140.2236 cm +q +q +1 0 0 1 0 0 cm +q +1 0 0 1 6.6 6.6 cm +q +.662745 .662745 .662745 RG +.5 w +.960784 .960784 .862745 rg +n -6 -6 468.6898 108 re B* +Q +q +BT 1 0 0 1 0 89.71 Tm 12 TL /F5 10 Tf .4 .4 .4 rg (>) Tj (>) Tj (>) Tj 0 0 0 rg ( ) Tj .666667 .133333 1 rg (@trace) Tj 0 0 0 rg T* .4 .4 .4 rg (...) Tj 0 0 0 rg ( ) Tj /F3 10 Tf 0 .501961 0 rg (def) Tj /F5 10 Tf 0 0 0 rg ( ) Tj 0 0 1 rg (f) Tj 0 0 0 rg (\() Tj (_func_) Tj (\):) Tj ( ) Tj /F3 10 Tf 0 .501961 0 rg (print) Tj /F5 10 Tf 0 0 0 rg ( ) Tj (f) Tj T* .4 .4 .4 rg (...) Tj 0 0 0 rg T* (Traceback) Tj ( ) Tj (\() Tj (most) Tj ( ) Tj (recent) Tj ( ) Tj (call) Tj ( ) Tj (last) Tj (\):) Tj T* ( ) Tj .4 .4 .4 rg (...) Tj 0 0 0 rg T* /F3 10 Tf .823529 .254902 .227451 rg (NameError) Tj /F5 10 Tf 0 0 0 rg (:) Tj ( ) Tj (_func_) Tj ( ) Tj /F3 10 Tf .666667 .133333 1 rg (is) Tj /F5 10 Tf 0 0 0 rg ( ) Tj (overridden) Tj ( ) Tj /F3 10 Tf .666667 .133333 1 rg (in) Tj /F5 10 Tf 0 0 0 rg T* /F3 10 Tf 0 .501961 0 rg (def) Tj /F5 10 Tf 0 0 0 rg ( ) Tj 0 0 1 rg (f) Tj 0 0 0 rg (\() Tj (_func_) Tj (\):) Tj T* ( ) Tj /F3 10 Tf 0 .501961 0 rg (return) Tj /F5 10 Tf 0 0 0 rg ( ) Tj (_call_) Tj (\() Tj (_func_) Tj (,) Tj ( ) Tj (_func_) Tj (\)) Tj T* ET +Q +Q +Q +Q +Q +q +1 0 0 1 62.69291 108.2236 cm +q +BT 1 0 0 1 0 16.82 Tm 1.533318 Tw 12 TL /F1 10 Tf 0 0 0 rg (Finally, the implementation is such that the decorated function contains a ) Tj /F6 10 Tf (copy ) Tj /F1 10 Tf (of the original function) Tj T* 0 Tw (dictionary \() Tj /F5 10 Tf (vars\(decorated_f\) is not vars\(f\)) Tj /F1 10 Tf (\):) Tj T* ET +Q +Q + +endstream + +endobj +% 'R95': class PDFStream +95 0 obj +% page stream +<< /Length 7179 >> +stream +1 0 0 1 0 0 cm BT /F1 12 Tf 14.4 TL ET +q +1 0 0 1 62.69291 619.8236 cm +q +q +1 0 0 1 0 0 cm +q +1 0 0 1 6.6 6.6 cm +q +.662745 .662745 .662745 RG +.5 w +.960784 .960784 .862745 rg +n -6 -6 468.6898 144 re B* +Q +q +BT 1 0 0 1 0 125.71 Tm 12 TL /F5 10 Tf .4 .4 .4 rg (>) Tj (>) Tj (>) Tj 0 0 0 rg ( ) Tj /F3 10 Tf 0 .501961 0 rg (def) Tj /F5 10 Tf 0 0 0 rg ( ) Tj 0 0 1 rg (f) Tj 0 0 0 rg (\(\):) Tj ( ) Tj /F3 10 Tf 0 .501961 0 rg (pass) Tj /F5 10 Tf 0 0 0 rg ( ) Tj /F7 10 Tf .25098 .501961 .501961 rg (# the original function) Tj /F5 10 Tf 0 0 0 rg T* .4 .4 .4 rg (>) Tj (>) Tj (>) Tj 0 0 0 rg ( ) Tj (f) Tj .4 .4 .4 rg (.) Tj 0 0 0 rg (attr1) Tj ( ) Tj .4 .4 .4 rg (=) Tj 0 0 0 rg ( ) Tj .729412 .129412 .129412 rg ("something") Tj 0 0 0 rg ( ) Tj /F7 10 Tf .25098 .501961 .501961 rg (# setting an attribute) Tj /F5 10 Tf 0 0 0 rg T* .4 .4 .4 rg (>) Tj (>) Tj (>) Tj 0 0 0 rg ( ) Tj (f) Tj .4 .4 .4 rg (.) Tj 0 0 0 rg (attr2) Tj ( ) Tj .4 .4 .4 rg (=) Tj 0 0 0 rg ( ) Tj .729412 .129412 .129412 rg ("something else") Tj 0 0 0 rg ( ) Tj /F7 10 Tf .25098 .501961 .501961 rg (# setting another attribute) Tj /F5 10 Tf 0 0 0 rg T* T* .4 .4 .4 rg (>) Tj (>) Tj (>) Tj 0 0 0 rg ( ) Tj (traced_f) Tj ( ) Tj .4 .4 .4 rg (=) Tj 0 0 0 rg ( ) Tj (trace) Tj (\() Tj (f) Tj (\)) Tj ( ) Tj /F7 10 Tf .25098 .501961 .501961 rg (# the decorated function) Tj /F5 10 Tf 0 0 0 rg T* T* .4 .4 .4 rg (>) Tj (>) Tj (>) Tj 0 0 0 rg ( ) Tj (traced_f) Tj .4 .4 .4 rg (.) Tj 0 0 0 rg (attr1) Tj T* .729412 .129412 .129412 rg ('something') Tj 0 0 0 rg T* .4 .4 .4 rg (>) Tj (>) Tj (>) Tj 0 0 0 rg ( ) Tj (traced_f) Tj .4 .4 .4 rg (.) Tj 0 0 0 rg (attr2) Tj ( ) Tj .4 .4 .4 rg (=) Tj 0 0 0 rg ( ) Tj .729412 .129412 .129412 rg ("something different") Tj 0 0 0 rg ( ) Tj /F7 10 Tf .25098 .501961 .501961 rg (# setting attr) Tj /F5 10 Tf 0 0 0 rg T* .4 .4 .4 rg (>) Tj (>) Tj (>) Tj 0 0 0 rg ( ) Tj (f) Tj .4 .4 .4 rg (.) Tj 0 0 0 rg (attr2) Tj ( ) Tj /F7 10 Tf .25098 .501961 .501961 rg (# the original attribute did not change) Tj /F5 10 Tf 0 0 0 rg T* .729412 .129412 .129412 rg ('something else') Tj T* ET +Q +Q +Q +Q +Q +q +1 0 0 1 62.69291 586.8236 cm +q +BT 1 0 0 1 0 8.435 Tm 21 TL /F2 17.5 Tf 0 0 0 rg (Compatibility notes) Tj T* ET +Q +Q +q +1 0 0 1 62.69291 520.8236 cm +q +BT 1 0 0 1 0 52.82 Tm 1.19686 Tw 12 TL /F1 10 Tf 0 0 0 rg (Version 3.2 is the first version of the ) Tj /F5 10 Tf (decorator ) Tj /F1 10 Tf (module to officially support Python 3.0. Actually, the) Tj T* 0 Tw 1.33311 Tw (module has supported Python 3.0 from the beginning, via the ) Tj /F5 10 Tf (2to3 ) Tj /F1 10 Tf (conversion tool, but this step has) Tj T* 0 Tw 2.714269 Tw (been now integrated in the build process, thanks to the ) Tj 0 0 .501961 rg (distribute ) Tj 0 0 0 rg (project, the Python 3-compatible) Tj T* 0 Tw 1.961412 Tw (replacement of easy_install. The hard work \(for me\) has been converting the documentation and the) Tj T* 0 Tw (doctests. This has been possible only now that ) Tj 0 0 .501961 rg (docutils ) Tj 0 0 0 rg (and ) Tj 0 0 .501961 rg (pygments ) Tj 0 0 0 rg (have been ported to Python 3.) Tj T* ET +Q +Q +q +1 0 0 1 62.69291 442.8236 cm +q +BT 1 0 0 1 0 64.82 Tm 1.19561 Tw 12 TL /F1 10 Tf 0 0 0 rg (The ) Tj /F5 10 Tf (decorator ) Tj /F1 10 Tf (module ) Tj /F6 10 Tf (per se ) Tj /F1 10 Tf (does not contain any change, apart from the removal of the functions) Tj T* 0 Tw 1.348314 Tw /F5 10 Tf (get_info ) Tj /F1 10 Tf (and ) Tj /F5 10 Tf (new_wrapper) Tj /F1 10 Tf (, which have been deprecated for years. ) Tj /F5 10 Tf (get_info ) Tj /F1 10 Tf (has been removed) Tj T* 0 Tw .921654 Tw (since it was little used and since it had to be changed anyway to work with Python 3.0; ) Tj /F5 10 Tf (new_wrapper) Tj T* 0 Tw .609318 Tw /F1 10 Tf (has been removed since it was useless: its major use case \(converting signature changing decorators to) Tj T* 0 Tw .028443 Tw (signature preserving decorators\) has been subsumed by ) Tj /F5 10 Tf (decorator_apply ) Tj /F1 10 Tf (and the other use case can) Tj T* 0 Tw (be managed with the ) Tj /F5 10 Tf (FunctionMaker) Tj /F1 10 Tf (.) Tj T* ET +Q +Q +q +1 0 0 1 62.69291 376.8236 cm +q +BT 1 0 0 1 0 52.82 Tm 1.329213 Tw 12 TL /F1 10 Tf 0 0 0 rg (There are a few changes in the documentation: I removed the ) Tj /F5 10 Tf (decorator_factory ) Tj /F1 10 Tf (example, which) Tj T* 0 Tw 2.562927 Tw (was confusing some of my users, and I removed the part about exotic signatures in the Python 3) Tj T* 0 Tw 2.20061 Tw (documentation, since Python 3 does not support them. Notice that there is no support for Python 3) Tj T* 0 Tw 1.163984 Tw 0 0 .501961 rg (function annotations ) Tj 0 0 0 rg (since it seems premature at the moment, when most people are still using Python) Tj T* 0 Tw (2.X.) Tj T* ET +Q +Q +q +1 0 0 1 62.69291 310.8236 cm +q +BT 1 0 0 1 0 52.82 Tm .942651 Tw 12 TL /F1 10 Tf 0 0 0 rg (Finally ) Tj /F5 10 Tf (decorator ) Tj /F1 10 Tf (cannot be used as a class decorator and the ) Tj 0 0 .501961 rg (functionality introduced in version 2.3) Tj T* 0 Tw .241163 Tw 0 0 0 rg (has been removed. That means that in order to define decorator factories with classes you need to define) Tj T* 0 Tw 1.122126 Tw (the ) Tj /F5 10 Tf (__call__ ) Tj /F1 10 Tf (method explicitly \(no magic anymore\). All these changes should not cause any trouble,) Tj T* 0 Tw .601163 Tw (since they were all rarely used features. Should you have any trouble, you can always downgrade to the) Tj T* 0 Tw (2.3 version.) Tj T* ET +Q +Q +q +1 0 0 1 62.69291 244.8236 cm +q +BT 1 0 0 1 0 52.82 Tm .196098 Tw 12 TL /F1 10 Tf 0 0 0 rg (The examples shown here have been tested with Python 2.6. Python 2.4 is also supported - of course the) Tj T* 0 Tw 1.649398 Tw (examples requiring the ) Tj /F5 10 Tf (with ) Tj /F1 10 Tf (statement will not work there. Python 2.5 works fine, but if you run the) Tj T* 0 Tw 1.41784 Tw (examples in the interactive interpreter you will notice a few differences since ) Tj /F5 10 Tf (getargspec ) Tj /F1 10 Tf (returns an) Tj T* 0 Tw .909982 Tw /F5 10 Tf (ArgSpec ) Tj /F1 10 Tf (namedtuple instead of a regular tuple. That means that running the file ) Tj /F5 10 Tf (documentation.py) Tj T* 0 Tw /F1 10 Tf (under Python 2.5 will print a few errors, but they are not serious.) Tj T* ET +Q +Q +q +1 0 0 1 62.69291 211.8236 cm +q +BT 1 0 0 1 0 8.435 Tm 21 TL /F2 17.5 Tf 0 0 0 rg (LICENCE) Tj T* ET +Q +Q +q +1 0 0 1 62.69291 181.8236 cm +q +0 0 0 rg +BT 1 0 0 1 0 16.82 Tm /F1 10 Tf 12 TL 1.328555 Tw (Redistribution and use in source and binary forms, with or without modification, are permitted provided) Tj T* 0 Tw (that the following conditions are met:) Tj T* ET +Q +Q +q +1 0 0 1 62.69291 88.62362 cm +q +q +1 0 0 1 0 0 cm +q +1 0 0 1 6.6 6.6 cm +q +.662745 .662745 .662745 RG +.5 w +.960784 .960784 .862745 rg +n -6 -6 468.6898 84 re B* +Q +q +0 0 0 rg +BT 1 0 0 1 0 65.71 Tm /F5 10 Tf 12 TL (Copyright \(c\) 2005, Michele Simionato) Tj T* (All rights reserved.) Tj T* T* (Redistributions of source code must retain the above copyright) Tj T* (notice, this list of conditions and the following disclaimer.) Tj T* (Redistributions in bytecode form must reproduce the above copyright) Tj T* ET +Q +Q +Q +Q +Q + +endstream + +endobj +% 'R96': class PDFStream +96 0 obj +% page stream +<< /Length 1630 >> +stream +1 0 0 1 0 0 cm BT /F1 12 Tf 14.4 TL ET +q +1 0 0 1 62.69291 559.8236 cm +q +q +1 0 0 1 0 0 cm +q +1 0 0 1 6.6 6.6 cm +q +.662745 .662745 .662745 RG +.5 w +.960784 .960784 .862745 rg +n -6 -6 468.6898 204 re B* +Q +q +0 0 0 rg +BT 1 0 0 1 0 185.71 Tm /F5 10 Tf 12 TL (notice, this list of conditions and the following disclaimer in) Tj T* (the documentation and/or other materials provided with the) Tj T* (distribution.) Tj T* T* (THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS) Tj T* ("AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT) Tj T* (LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR) Tj T* (A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT) Tj T* (HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,) Tj T* (INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES \(INCLUDING,) Tj T* (BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS) Tj T* (OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION\) HOWEVER CAUSED AND) Tj T* (ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR) Tj T* (TORT \(INCLUDING NEGLIGENCE OR OTHERWISE\) ARISING IN ANY WAY OUT OF THE) Tj T* (USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH) Tj T* (DAMAGE.) Tj T* ET +Q +Q +Q +Q +Q +q +1 0 0 1 62.69291 527.8236 cm +q +0 0 0 rg +BT 1 0 0 1 0 16.82 Tm /F1 10 Tf 12 TL .407132 Tw (If you use this software and you are happy with it, consider sending me a note, just to gratify my ego. On) Tj T* 0 Tw (the other hand, if you use this software and you are unhappy with it, send me a patch!) Tj T* ET +Q +Q + +endstream + +endobj +% 'R97': class PDFPageLabels +97 0 obj +% Document Root +<< /Nums [ 0 + 98 0 R + 1 + 99 0 R + 2 + 100 0 R + 3 + 101 0 R + 4 + 102 0 R + 5 + 103 0 R + 6 + 104 0 R + 7 + 105 0 R + 8 + 106 0 R + 9 + 107 0 R + 10 + 108 0 R + 11 + 109 0 R + 12 + 110 0 R + 13 + 111 0 R + 14 + 112 0 R ] >> +endobj +% 'R98': class PDFPageLabel +98 0 obj +% None +<< /S /D + /St 1 >> +endobj +% 'R99': class PDFPageLabel +99 0 obj +% None +<< /S /D + /St 2 >> +endobj +% 'R100': class PDFPageLabel +100 0 obj +% None +<< /S /D + /St 3 >> +endobj +% 'R101': class PDFPageLabel +101 0 obj +% None +<< /S /D + /St 4 >> +endobj +% 'R102': class PDFPageLabel +102 0 obj +% None +<< /S /D + /St 5 >> +endobj +% 'R103': class PDFPageLabel +103 0 obj +% None +<< /S /D + /St 6 >> +endobj +% 'R104': class PDFPageLabel +104 0 obj +% None +<< /S /D + /St 7 >> +endobj +% 'R105': class PDFPageLabel +105 0 obj +% None +<< /S /D + /St 8 >> +endobj +% 'R106': class PDFPageLabel +106 0 obj +% None +<< /S /D + /St 9 >> +endobj +% 'R107': class PDFPageLabel +107 0 obj +% None +<< /S /D + /St 10 >> +endobj +% 'R108': class PDFPageLabel +108 0 obj +% None +<< /S /D + /St 11 >> +endobj +% 'R109': class PDFPageLabel +109 0 obj +% None +<< /S /D + /St 12 >> +endobj +% 'R110': class PDFPageLabel +110 0 obj +% None +<< /S /D + /St 13 >> +endobj +% 'R111': class PDFPageLabel +111 0 obj +% None +<< /S /D + /St 14 >> +endobj +% 'R112': class PDFPageLabel +112 0 obj +% None +<< /S /D + /St 15 >> +endobj +xref +0 113 +0000000000 65535 f +0000000113 00000 n +0000000283 00000 n +0000000448 00000 n +0000000623 00000 n +0000000794 00000 n +0000000975 00000 n +0000001227 00000 n +0000001476 00000 n +0000001650 00000 n +0000001891 00000 n +0000002133 00000 n +0000002375 00000 n +0000002617 00000 n +0000002859 00000 n +0000003101 00000 n +0000003344 00000 n +0000003587 00000 n +0000003830 00000 n +0000004073 00000 n +0000004315 00000 n +0000004557 00000 n +0000004800 00000 n +0000005043 00000 n +0000005286 00000 n +0000005529 00000 n +0000005772 00000 n +0000006015 00000 n +0000006258 00000 n +0000006501 00000 n +0000006744 00000 n +0000006987 00000 n +0000007230 00000 n +0000007473 00000 n +0000007716 00000 n +0000007959 00000 n +0000008202 00000 n +0000008429 00000 n +0000008990 00000 n +0000009185 00000 n +0000009441 00000 n +0000009632 00000 n +0000009892 00000 n +0000010202 00000 n +0000010482 00000 n +0000010762 00000 n +0000011042 00000 n +0000011322 00000 n +0000011602 00000 n +0000011882 00000 n +0000012177 00000 n +0000012432 00000 n +0000012700 00000 n +0000013011 00000 n +0000013292 00000 n +0000013587 00000 n +0000013832 00000 n +0000014148 00000 n +0000014406 00000 n +0000014658 00000 n +0000014898 00000 n +0000015158 00000 n +0000015465 00000 n +0000015803 00000 n +0000016084 00000 n +0000016243 00000 n +0000016492 00000 n +0000016618 00000 n +0000016791 00000 n +0000016978 00000 n +0000017178 00000 n +0000017366 00000 n +0000017559 00000 n +0000017758 00000 n +0000017942 00000 n +0000018123 00000 n +0000018322 00000 n +0000018522 00000 n +0000018734 00000 n +0000018934 00000 n +0000019130 00000 n +0000019282 00000 n +0000019517 00000 n +0000028721 00000 n +0000036458 00000 n +0000044610 00000 n +0000051869 00000 n +0000060799 00000 n +0000068075 00000 n +0000075065 00000 n +0000082434 00000 n +0000090723 00000 n +0000098130 00000 n +0000106120 00000 n +0000111225 00000 n +0000118852 00000 n +0000126132 00000 n +0000127867 00000 n +0000128160 00000 n +0000128237 00000 n +0000128315 00000 n +0000128394 00000 n +0000128473 00000 n +0000128552 00000 n +0000128631 00000 n +0000128710 00000 n +0000128789 00000 n +0000128868 00000 n +0000128948 00000 n +0000129028 00000 n +0000129108 00000 n +0000129188 00000 n +0000129268 00000 n +trailer +<< /ID + % ReportLab generated PDF document -- digest (http://www.reportlab.com) + [(\342\333\011\351bn\010V+\372x^\354\375\236h) (\342\333\011\351bn\010V+\372x^\354\375\236h)] + + /Info 65 0 R + /Root 64 0 R + /Size 113 >> +startxref +129317 +%%EOF diff --git a/documentation.py b/documentation.py index aff5d17..acf6641 100644 --- a/documentation.py +++ b/documentation.py @@ -83,11 +83,11 @@ the function is called with the same input parameters the result is retrieved from the cache and not recomputed. There are many implementations of ``memoize`` in http://www.python.org/moin/PythonDecoratorLibrary, but they do not preserve the signature. -A simple implementation for Python 2.5 could be the following (notice +A simple implementation could be the following (notice that in general it is impossible to memoize correctly something that depends on non-hashable arguments): -$$memoize25 +$$memoize_uw Here we used the functools.update_wrapper_ utility, which has been added in Python 2.5 expressly to simplify the definition of decorators @@ -100,14 +100,14 @@ from the original function to the decorated function by hand). The implementation above works in the sense that the decorator can accept functions with generic signatures; unfortunately this implementation does *not* define a signature-preserving decorator, since in -general ``memoize25`` returns a function with a +general ``memoize_uw`` returns a function with a *different signature* from the original function. Consider for instance the following case: .. code-block:: python - >>> @memoize25 + >>> @memoize_uw ... def f1(x): ... time.sleep(1) # simulate some long computation ... return x @@ -119,7 +119,7 @@ keyword arguments: .. code-block:: python >>> from inspect import getargspec - >>> print getargspec(f1) + >>> print getargspec(f1) # I am using Python 2.6+ here ArgSpec(args=[], varargs='args', keywords='kw', defaults=None) This means that introspection tools such as pydoc will give @@ -160,7 +160,7 @@ At this point you can define your decorator as follows: $$memoize -The difference with respect to the Python 2.5 approach, which is based +The difference with respect to the ``memoize_uw`` approach, which is based on nested functions, is that the decorator module forces you to lift the inner function at the outer level (*flat is better than nested*). Moreover, you are forced to pass explicitly the function you want to @@ -732,12 +732,12 @@ Compatibility notes --------------------------------------------------------------- Version 3.2 is the first version of the ``decorator`` module to officially -support Python 3.0. Actually, the module has supported Python 3.0 from +support Python 3. Actually, the module has supported Python 3 from the beginning, via the ``2to3`` conversion tool, but this step has been now integrated in the build process, thanks to the distribute_ project, the Python 3-compatible replacement of easy_install. The hard work (for me) has been converting the documentation and the -doctests. This has been possibly only now that docutils_ and pygments_ +doctests. This has been possible only now that docutils_ and pygments_ have been ported to Python 3. The ``decorator`` module *per se* does not contain any change, apart @@ -769,11 +769,11 @@ downgrade to the 2.3 version. The examples shown here have been tested with Python 2.6. Python 2.4 is also supported - of course the examples requiring the ``with`` statement will not work there. Python 2.5 works fine, but if you -run the examples here in the interactive interpreter +run the examples in the interactive interpreter you will notice a few differences since ``getargspec`` returns an ``ArgSpec`` namedtuple instead of a regular tuple. That means that running the file -``documentation.py`` under Python 2.5 will a few errors, but +``documentation.py`` under Python 2.5 will print a few errors, but they are not serious. .. _functionality introduced in version 2.3: http://www.phyast.pitt.edu/~micheles/python/documentation.html#class-decorators-and-decorator-factories @@ -898,7 +898,7 @@ def identity_dec(func): @identity_dec def example(): pass -def memoize25(func): +def memoize_uw(func): func.cache = {} def memoize(*args, **kw): if kw: # frozenset is used to ensure hashability diff --git a/documentation3.html b/documentation3.html index 209dd61..aabb303 100644 --- a/documentation3.html +++ b/documentation3.html @@ -176,25 +176,27 @@ the function is called with the same input parameters the result is retrieved from the cache and not recomputed. There are many implementations of memoize in http://www.python.org/moin/PythonDecoratorLibrary, but they do not preserve the signature. -A simple implementation for Python 2.5 could be the following (notice +A simple implementation could be the following (notice that in general it is impossible to memoize correctly something that depends on non-hashable arguments):

-
-def memoize25(func):
-    func.cache = {}
-    def memoize(*args, **kw):
-        if kw: # frozenset is used to ensure hashability
-            key = args, frozenset(kw.iteritems())
-        else:
-            key = args
-        cache = func.cache
-        if key in cache:
-            return cache[key]
-        else:
-            cache[key] = result = func(*args, **kw)
-            return result
-    return functools.update_wrapper(memoize, func)
-
+
+
def memoize_uw(func):
+    func.cache = {}
+    def memoize(*args, **kw):
+        if kw: # frozenset is used to ensure hashability
+            key = args, frozenset(kw.iteritems())
+        else:
+            key = args
+        cache = func.cache
+        if key in cache:
+            return cache[key]
+        else:
+            cache[key] = result = func(*args, **kw)
+            return result
+    return functools.update_wrapper(memoize, func)
+
+ +

Here we used the functools.update_wrapper utility, which has been added in Python 2.5 expressly to simplify the definition of decorators (in older versions of Python you need to copy the function attributes @@ -203,11 +205,11 @@ from the original function to the decorated function by hand).

The implementation above works in the sense that the decorator can accept functions with generic signatures; unfortunately this implementation does not define a signature-preserving decorator, since in -general memoize25 returns a function with a +general memoize_uw returns a function with a different signature from the original function.

Consider for instance the following case:

-
>>> @memoize25
+
>>> @memoize_uw
 ... def f1(x):
 ...     time.sleep(1) # simulate some long computation
 ...     return x
@@ -255,26 +257,30 @@ returns the decorated function. The caller function must have
 signature (f, *args, **kw) and it must call the original function f
 with arguments args and kw, implementing the wanted capability,
 i.e. memoization in this case:

-
-def _memoize(func, *args, **kw):
-    if kw: # frozenset is used to ensure hashability
-        key = args, frozenset(kw.iteritems())
-    else:
-        key = args
-    cache = func.cache # attributed added by memoize
-    if key in cache:
-        return cache[key]
-    else:
-        cache[key] = result = func(*args, **kw)
-        return result
-
+
+
def _memoize(func, *args, **kw):
+    if kw: # frozenset is used to ensure hashability
+        key = args, frozenset(kw.iteritems())
+    else:
+        key = args
+    cache = func.cache # attributed added by memoize
+    if key in cache:
+        return cache[key]
+    else:
+        cache[key] = result = func(*args, **kw)
+        return result
+
+ +

At this point you can define your decorator as follows:

-
-def memoize(f):
-    f.cache = {}
-    return decorator(_memoize, f)
-
-

The difference with respect to the Python 2.5 approach, which is based +

+
def memoize(f):
+    f.cache = {}
+    return decorator(_memoize, f)
+
+ +
+

The difference with respect to the memoize_uw approach, which is based on nested functions, is that the decorator module forces you to lift the inner function at the outer level (flat is better than nested). Moreover, you are forced to pass explicitly the function you want to @@ -307,15 +313,19 @@ decorate to the caller function.

As an additional example, here is how you can define a trivial trace decorator, which prints a message everytime the traced function is called:

-
-def _trace(f, *args, **kw):
-    print("calling %s with args %s, %s" % (f.__name__, args, kw))
-    return f(*args, **kw)
-
-
-def trace(f):
-    return decorator(_trace, f)
-
+
+
def _trace(f, *args, **kw):
+    print("calling %s with args %s, %s" % (f.__name__, args, kw))
+    return f(*args, **kw)
+
+ +
+
+
def trace(f):
+    return decorator(_trace, f)
+
+ +

Here is an example of usage:

>>> @trace
@@ -404,21 +414,23 @@ object which can be used as a decorator:

sometimes it is best to have back a "busy" message than to block everything. This behavior can be implemented with a suitable family of decorators, where the parameter is the busy message:

-
-def blocking(not_avail):
-    def blocking(f, *args, **kw):
-        if not hasattr(f, "thread"): # no thread running
-            def set_result(): f.result = f(*args, **kw)
-            f.thread = threading.Thread(None, set_result)
-            f.thread.start()
-            return not_avail
-        elif f.thread.isAlive():
-            return not_avail
-        else: # the thread is ended, return the stored result
-            del f.thread
-            return f.result
-    return decorator(blocking)
-
+
+
def blocking(not_avail):
+    def blocking(f, *args, **kw):
+        if not hasattr(f, "thread"): # no thread running
+            def set_result(): f.result = f(*args, **kw)
+            f.thread = threading.Thread(None, set_result)
+            f.thread.start()
+            return not_avail
+        elif f.thread.isAlive():
+            return not_avail
+        else: # the thread is ended, return the stored result
+            del f.thread
+            return f.result
+    return decorator(blocking)
+
+ +

Functions decorated with blocking will return a busy message if the resource is unavailable, and the intended result if the resource is available. For instance:

@@ -463,58 +475,66 @@ is executed in a separate thread. Moreover, it is possible to set three callbacks on_success, on_failure and on_closing, to specify how to manage the function call. The implementation is the following:

-
-def on_success(result): # default implementation
-    "Called on the result of the function"
-    return result
-
-
-def on_failure(exc_info): # default implementation
-    "Called if the function fails"
-    pass
-
-
-def on_closing(): # default implementation
-    "Called at the end, both in case of success and failure"
-    pass
-
-
-class Async(object):
-    """
-    A decorator converting blocking functions into asynchronous
-    functions, by using threads or processes. Examples:
-
-    async_with_threads =  Async(threading.Thread)
-    async_with_processes =  Async(multiprocessing.Process)
-    """
-
-    def __init__(self, threadfactory):
-        self.threadfactory = threadfactory
-
-    def __call__(self, func, on_success=on_success,
-                 on_failure=on_failure, on_closing=on_closing):
-        # every decorated function has its own independent thread counter
-        func.counter = itertools.count(1)
-        func.on_success = on_success
-        func.on_failure = on_failure
-        func.on_closing = on_closing
-        return decorator(self.call, func)
-
-    def call(self, func, *args, **kw):
-        def func_wrapper():
-            try:
-                result = func(*args, **kw)
-            except:
-                func.on_failure(sys.exc_info())
-            else:
-                return func.on_success(result)
-            finally:
-                func.on_closing()
-        name = '%s-%s' % (func.__name__, next(func.counter))
-        thread = self.threadfactory(None, func_wrapper, name)
-        thread.start()
-        return thread
-
+
+
def on_success(result): # default implementation
+    "Called on the result of the function"
+    return result
+
+ +
+
+
def on_failure(exc_info): # default implementation
+    "Called if the function fails"
+    pass
+
+ +
+
+
def on_closing(): # default implementation
+    "Called at the end, both in case of success and failure"
+    pass
+
+ +
+
+
class Async(object):
+    """
+    A decorator converting blocking functions into asynchronous
+    functions, by using threads or processes. Examples:
+
+    async_with_threads =  Async(threading.Thread)
+    async_with_processes =  Async(multiprocessing.Process)
+    """
+
+    def __init__(self, threadfactory):
+        self.threadfactory = threadfactory
+
+    def __call__(self, func, on_success=on_success,
+                 on_failure=on_failure, on_closing=on_closing):
+        # every decorated function has its own independent thread counter
+        func.counter = itertools.count(1)
+        func.on_success = on_success
+        func.on_failure = on_failure
+        func.on_closing = on_closing
+        return decorator(self.call, func)
+
+    def call(self, func, *args, **kw):
+        def func_wrapper():
+            try:
+                result = func(*args, **kw)
+            except:
+                func.on_failure(sys.exc_info())
+            else:
+                return func.on_success(result)
+            finally:
+                func.on_closing()
+        name = '%s-%s' % (func.__name__, next(func.counter))
+        thread = self.threadfactory(None, func_wrapper, name)
+        thread.start()
+        return thread
+
+ +

The decorated function returns the current execution thread, which can be stored and checked later, for instance to verify that the thread .isAlive().

@@ -639,12 +659,14 @@ available. In the past I have considered this acceptable, since inspect.getsource does not really work even with regular decorators. In that case inspect.getsource gives you the wrapper source code which is probably not what you want:

-
-def identity_dec(func):
-    def wrapper(*args, **kw):
-        return func(*args, **kw)
-    return wrapper
-
+
+
def identity_dec(func):
+    def wrapper(*args, **kw):
+        return func(*args, **kw)
+    return wrapper
+
+ +
@identity_dec
 def example(): pass
@@ -683,16 +705,18 @@ decorator is not signature-preserving. Therefore you may want an easy way to
 upgrade third party decorators to signature-preserving decorators without
 having to rewrite them in terms of decorator. You can use a
 FunctionMaker to implement that functionality as follows:

-
-def decorator_apply(dec, func):
-    """
-    Decorate a function by preserving the signature even if dec
-    is not a signature-preserving decorator.
-    """
-    return FunctionMaker.create(
-        func, 'return decorated(%(signature)s)',
-        dict(decorated=dec(func)), undecorated=func)
-
+
+
def decorator_apply(dec, func):
+    """
+    Decorate a function by preserving the signature even if dec
+    is not a signature-preserving decorator.
+    """
+    return FunctionMaker.create(
+        func, 'return decorated(%(signature)s)',
+        dict(decorated=dec(func)), undecorated=func)
+
+ +

decorator_apply sets the attribute .undecorated of the generated function to the original function, so that you can get the right source code.

@@ -706,51 +730,57 @@ pretty slick decorator that converts a tail-recursive function in an iterative function. I have shamelessly stolen the basic idea from Kay Schluehr's recipe in the Python Cookbook, http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/496691.

-
-class TailRecursive(object):
-    """
-    tail_recursive decorator based on Kay Schluehr's recipe
-    http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/496691
-    with improvements by me and George Sakkis.
-    """
-
-    def __init__(self, func):
-        self.func = func
-        self.firstcall = True
-        self.CONTINUE = object() # sentinel
-
-    def __call__(self, *args, **kwd):
-        CONTINUE = self.CONTINUE
-        if self.firstcall:
-            func = self.func
-            self.firstcall = False
-            try:
-                while True:
-                    result = func(*args, **kwd)
-                    if result is CONTINUE: # update arguments
-                        args, kwd = self.argskwd
-                    else: # last call
-                        return result
-            finally:
-                self.firstcall = True
-        else: # return the arguments of the tail call
-            self.argskwd = args, kwd
-            return CONTINUE
-
+
+
class TailRecursive(object):
+    """
+    tail_recursive decorator based on Kay Schluehr's recipe
+    http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/496691
+    with improvements by me and George Sakkis.
+    """
+
+    def __init__(self, func):
+        self.func = func
+        self.firstcall = True
+        self.CONTINUE = object() # sentinel
+
+    def __call__(self, *args, **kwd):
+        CONTINUE = self.CONTINUE
+        if self.firstcall:
+            func = self.func
+            self.firstcall = False
+            try:
+                while True:
+                    result = func(*args, **kwd)
+                    if result is CONTINUE: # update arguments
+                        args, kwd = self.argskwd
+                    else: # last call
+                        return result
+            finally:
+                self.firstcall = True
+        else: # return the arguments of the tail call
+            self.argskwd = args, kwd
+            return CONTINUE
+
+ +

Here the decorator is implemented as a class returning callable objects.

-
-def tail_recursive(func):
-    return decorator_apply(TailRecursive, func)
-
+
+
def tail_recursive(func):
+    return decorator_apply(TailRecursive, func)
+
+ +

Here is how you apply the upgraded decorator to the good old factorial:

-
-@tail_recursive
-def factorial(n, acc=1):
-    "The good old factorial"
-    if n == 0: return acc
-    return factorial(n-1, n*acc)
-
+
+
@tail_recursive
+def factorial(n, acc=1):
+    "The good old factorial"
+    if n == 0: return acc
+    return factorial(n-1, n*acc)
+
+ +
>>> print(factorial(4))
 24
@@ -762,11 +792,13 @@ your mind ;) Notice that there is no recursion limit now, and you can
 easily compute factorial(1001) or larger without filling the stack
 frame. Notice also that the decorator will not work on functions which
 are not tail recursive, such as the following

-
-def fact(n): # this is not tail-recursive
-    if n == 0: return 1
-    return n * fact(n-1)
-
+
+
def fact(n): # this is not tail-recursive
+    if n == 0: return 1
+    return n * fact(n-1)
+
+ +

(reminder: a function is tail recursive if it either returns a value without making a recursive call, or returns directly the result of a recursive call).

@@ -893,7 +925,7 @@ the beginning, via the 2to3 conversion tool, b been now integrated in the build process, thanks to the distribute project, the Python 3-compatible replacement of easy_install. The hard work (for me) has been converting the documentation and the -doctests. This has been possibly only now that docutils and pygments +doctests. This has been possible only now that docutils and pygments have been ported to Python 3.

The decorator module per se does not contain any change, apart from the removal of the functions get_info and new_wrapper, @@ -921,11 +953,11 @@ downgrade to the 2.3 version.

The examples shown here have been tested with Python 2.6. Python 2.4 is also supported - of course the examples requiring the with statement will not work there. Python 2.5 works fine, but if you -run the examples here in the interactive interpreter +run the examples in the interactive interpreter you will notice a few differences since getargspec returns an ArgSpec namedtuple instead of a regular tuple. That means that running the file -documentation.py under Python 2.5 will a few errors, but +documentation.py under Python 2.5 will print a few errors, but they are not serious.

diff --git a/documentation3.pdf b/documentation3.pdf new file mode 100644 index 0000000..05e0f52 --- /dev/null +++ b/documentation3.pdf @@ -0,0 +1,3666 @@ +%PDF-1.3 +%“Œ‹ž ReportLab Generated PDF document http://www.reportlab.com +% 'BasicFonts': class PDFDictionary +1 0 obj +% The standard fonts dictionary +<< /F1 2 0 R + /F2 3 0 R + /F3 4 0 R + /F4 5 0 R + /F5 8 0 R + /F6 38 0 R + /F7 40 0 R >> +endobj +% 'F1': class PDFType1Font +2 0 obj +% Font Helvetica +<< /BaseFont /Helvetica + /Encoding /WinAnsiEncoding + /Name /F1 + /Subtype /Type1 + /Type /Font >> +endobj +% 'F2': class PDFType1Font +3 0 obj +% Font Helvetica-Bold +<< /BaseFont /Helvetica-Bold + /Encoding /WinAnsiEncoding + /Name /F2 + /Subtype /Type1 + /Type /Font >> +endobj +% 'F3': class PDFType1Font +4 0 obj +% Font Courier-Bold +<< /BaseFont /Courier-Bold + /Encoding /WinAnsiEncoding + /Name /F3 + /Subtype /Type1 + /Type /Font >> +endobj +% 'F4': class PDFType1Font +5 0 obj +% Font Times-Roman +<< /BaseFont /Times-Roman + /Encoding /WinAnsiEncoding + /Name /F4 + /Subtype /Type1 + /Type /Font >> +endobj +% 'Annot.NUMBER1': class PDFDictionary +6 0 obj +<< /A << /S /URI + /Type /Action + /URI (mailto:michele.simionato@gmail.com) >> + /Border [ 0 + 0 + 0 ] + /Rect [ 153.7323 + 707.5936 + 526.5827 + 719.5936 ] + /Subtype /Link + /Type /Annot >> +endobj +% 'Annot.NUMBER2': class PDFDictionary +7 0 obj +<< /A << /S /URI + /Type /Action + /URI (http://pypi.python.org/pypi/decorator/3.2.0) >> + /Border [ 0 + 0 + 0 ] + /Rect [ 153.7323 + 662.5936 + 526.5827 + 674.5936 ] + /Subtype /Link + /Type /Annot >> +endobj +% 'F5': class PDFType1Font +8 0 obj +% Font Courier +<< /BaseFont /Courier + /Encoding /WinAnsiEncoding + /Name /F5 + /Subtype /Type1 + /Type /Font >> +endobj +% 'Annot.NUMBER3': class LinkAnnotation +9 0 obj +<< /Border [ 0 + 0 + 0 ] + /Contents () + /Dest [ 37 0 R + /XYZ + 62.69291 + 311.0236 + 0 ] + /Rect [ 62.69291 + 563.5936 + 121.0229 + 575.5936 ] + /Subtype /Link + /Type /Annot >> +endobj +% 'Annot.NUMBER4': class LinkAnnotation +10 0 obj +<< /Border [ 0 + 0 + 0 ] + /Contents () + /Dest [ 37 0 R + /XYZ + 62.69291 + 311.0236 + 0 ] + /Rect [ 527.0227 + 563.5936 + 532.5827 + 575.5936 ] + /Subtype /Link + /Type /Annot >> +endobj +% 'Annot.NUMBER5': class LinkAnnotation +11 0 obj +<< /Border [ 0 + 0 + 0 ] + /Contents () + /Dest [ 42 0 R + /XYZ + 62.69291 + 675.0236 + 0 ] + /Rect [ 62.69291 + 545.5936 + 114.3629 + 557.5936 ] + /Subtype /Link + /Type /Annot >> +endobj +% 'Annot.NUMBER6': class LinkAnnotation +12 0 obj +<< /Border [ 0 + 0 + 0 ] + /Contents () + /Dest [ 42 0 R + /XYZ + 62.69291 + 675.0236 + 0 ] + /Rect [ 527.0227 + 545.5936 + 532.5827 + 557.5936 ] + /Subtype /Link + /Type /Annot >> +endobj +% 'Annot.NUMBER7': class LinkAnnotation +13 0 obj +<< /Border [ 0 + 0 + 0 ] + /Contents () + /Dest [ 42 0 R + /XYZ + 62.69291 + 432.0236 + 0 ] + /Rect [ 62.69291 + 527.5936 + 183.2629 + 539.5936 ] + /Subtype /Link + /Type /Annot >> +endobj +% 'Annot.NUMBER8': class LinkAnnotation +14 0 obj +<< /Border [ 0 + 0 + 0 ] + /Contents () + /Dest [ 42 0 R + /XYZ + 62.69291 + 432.0236 + 0 ] + /Rect [ 527.0227 + 527.5936 + 532.5827 + 539.5936 ] + /Subtype /Link + /Type /Annot >> +endobj +% 'Annot.NUMBER9': class LinkAnnotation +15 0 obj +<< /Border [ 0 + 0 + 0 ] + /Contents () + /Dest [ 43 0 R + /XYZ + 62.69291 + 427.4236 + 0 ] + /Rect [ 62.69291 + 509.5936 + 122.1429 + 521.5936 ] + /Subtype /Link + /Type /Annot >> +endobj +% 'Annot.NUMBER10': class LinkAnnotation +16 0 obj +<< /Border [ 0 + 0 + 0 ] + /Contents () + /Dest [ 43 0 R + /XYZ + 62.69291 + 427.4236 + 0 ] + /Rect [ 527.0227 + 509.5936 + 532.5827 + 521.5936 ] + /Subtype /Link + /Type /Annot >> +endobj +% 'Annot.NUMBER11': class LinkAnnotation +17 0 obj +<< /Border [ 0 + 0 + 0 ] + /Contents () + /Dest [ 44 0 R + /XYZ + 62.69291 + 435.4236 + 0 ] + /Rect [ 62.69291 + 491.5936 + 154.8129 + 503.5936 ] + /Subtype /Link + /Type /Annot >> +endobj +% 'Annot.NUMBER12': class LinkAnnotation +18 0 obj +<< /Border [ 0 + 0 + 0 ] + /Contents () + /Dest [ 44 0 R + /XYZ + 62.69291 + 435.4236 + 0 ] + /Rect [ 527.0227 + 491.5936 + 532.5827 + 503.5936 ] + /Subtype /Link + /Type /Annot >> +endobj +% 'Annot.NUMBER13': class LinkAnnotation +19 0 obj +<< /Border [ 0 + 0 + 0 ] + /Contents () + /Dest [ 45 0 R + /XYZ + 62.69291 + 567.978 + 0 ] + /Rect [ 62.69291 + 473.5936 + 188.2729 + 485.5936 ] + /Subtype /Link + /Type /Annot >> +endobj +% 'Annot.NUMBER14': class LinkAnnotation +20 0 obj +<< /Border [ 0 + 0 + 0 ] + /Contents () + /Dest [ 45 0 R + /XYZ + 62.69291 + 567.978 + 0 ] + /Rect [ 527.0227 + 473.5936 + 532.5827 + 485.5936 ] + /Subtype /Link + /Type /Annot >> +endobj +% 'Annot.NUMBER15': class LinkAnnotation +21 0 obj +<< /Border [ 0 + 0 + 0 ] + /Contents () + /Dest [ 45 0 R + /XYZ + 62.69291 + 153.378 + 0 ] + /Rect [ 62.69291 + 455.5936 + 110.6929 + 467.5936 ] + /Subtype /Link + /Type /Annot >> +endobj +% 'Annot.NUMBER16': class LinkAnnotation +22 0 obj +<< /Border [ 0 + 0 + 0 ] + /Contents () + /Dest [ 45 0 R + /XYZ + 62.69291 + 153.378 + 0 ] + /Rect [ 527.0227 + 455.5936 + 532.5827 + 467.5936 ] + /Subtype /Link + /Type /Annot >> +endobj +% 'Annot.NUMBER17': class LinkAnnotation +23 0 obj +<< /Border [ 0 + 0 + 0 ] + /Contents () + /Dest [ 46 0 R + /XYZ + 62.69291 + 302.6236 + 0 ] + /Rect [ 62.69291 + 437.5936 + 92.69291 + 449.5936 ] + /Subtype /Link + /Type /Annot >> +endobj +% 'Annot.NUMBER18': class LinkAnnotation +24 0 obj +<< /Border [ 0 + 0 + 0 ] + /Contents () + /Dest [ 46 0 R + /XYZ + 62.69291 + 302.6236 + 0 ] + /Rect [ 527.0227 + 437.5936 + 532.5827 + 449.5936 ] + /Subtype /Link + /Type /Annot >> +endobj +% 'Annot.NUMBER19': class LinkAnnotation +25 0 obj +<< /Border [ 0 + 0 + 0 ] + /Contents () + /Dest [ 48 0 R + /XYZ + 62.69291 + 446.6236 + 0 ] + /Rect [ 62.69291 + 419.5936 + 192.2729 + 431.5936 ] + /Subtype /Link + /Type /Annot >> +endobj +% 'Annot.NUMBER20': class LinkAnnotation +26 0 obj +<< /Border [ 0 + 0 + 0 ] + /Contents () + /Dest [ 48 0 R + /XYZ + 62.69291 + 446.6236 + 0 ] + /Rect [ 527.0227 + 419.5936 + 532.5827 + 431.5936 ] + /Subtype /Link + /Type /Annot >> +endobj +% 'Annot.NUMBER21': class LinkAnnotation +27 0 obj +<< /Border [ 0 + 0 + 0 ] + /Contents () + /Dest [ 50 0 R + /XYZ + 62.69291 + 449.8236 + 0 ] + /Rect [ 62.69291 + 401.5936 + 177.1629 + 413.5936 ] + /Subtype /Link + /Type /Annot >> +endobj +% 'Annot.NUMBER22': class LinkAnnotation +28 0 obj +<< /Border [ 0 + 0 + 0 ] + /Contents () + /Dest [ 50 0 R + /XYZ + 62.69291 + 449.8236 + 0 ] + /Rect [ 527.0227 + 401.5936 + 532.5827 + 413.5936 ] + /Subtype /Link + /Type /Annot >> +endobj +% 'Annot.NUMBER23': class LinkAnnotation +29 0 obj +<< /Border [ 0 + 0 + 0 ] + /Contents () + /Dest [ 52 0 R + /XYZ + 62.69291 + 655.8236 + 0 ] + /Rect [ 62.69291 + 383.5936 + 228.2829 + 395.5936 ] + /Subtype /Link + /Type /Annot >> +endobj +% 'Annot.NUMBER24': class LinkAnnotation +30 0 obj +<< /Border [ 0 + 0 + 0 ] + /Contents () + /Dest [ 52 0 R + /XYZ + 62.69291 + 655.8236 + 0 ] + /Rect [ 521.4627 + 383.5936 + 532.5827 + 395.5936 ] + /Subtype /Link + /Type /Annot >> +endobj +% 'Annot.NUMBER25': class LinkAnnotation +31 0 obj +<< /Border [ 0 + 0 + 0 ] + /Contents () + /Dest [ 53 0 R + /XYZ + 62.69291 + 263.0236 + 0 ] + /Rect [ 62.69291 + 365.5936 + 174.3929 + 377.5936 ] + /Subtype /Link + /Type /Annot >> +endobj +% 'Annot.NUMBER26': class LinkAnnotation +32 0 obj +<< /Border [ 0 + 0 + 0 ] + /Contents () + /Dest [ 53 0 R + /XYZ + 62.69291 + 263.0236 + 0 ] + /Rect [ 521.4627 + 365.5936 + 532.5827 + 377.5936 ] + /Subtype /Link + /Type /Annot >> +endobj +% 'Annot.NUMBER27': class LinkAnnotation +33 0 obj +<< /Border [ 0 + 0 + 0 ] + /Contents () + /Dest [ 61 0 R + /XYZ + 62.69291 + 426.6236 + 0 ] + /Rect [ 62.69291 + 347.5936 + 155.4829 + 359.5936 ] + /Subtype /Link + /Type /Annot >> +endobj +% 'Annot.NUMBER28': class LinkAnnotation +34 0 obj +<< /Border [ 0 + 0 + 0 ] + /Contents () + /Dest [ 61 0 R + /XYZ + 62.69291 + 426.6236 + 0 ] + /Rect [ 521.4627 + 347.5936 + 532.5827 + 359.5936 ] + /Subtype /Link + /Type /Annot >> +endobj +% 'Annot.NUMBER29': class LinkAnnotation +35 0 obj +<< /Border [ 0 + 0 + 0 ] + /Contents () + /Dest [ 62 0 R + /XYZ + 62.69291 + 729.0236 + 0 ] + /Rect [ 62.69291 + 329.5936 + 106.5829 + 341.5936 ] + /Subtype /Link + /Type /Annot >> +endobj +% 'Annot.NUMBER30': class LinkAnnotation +36 0 obj +<< /Border [ 0 + 0 + 0 ] + /Contents () + /Dest [ 62 0 R + /XYZ + 62.69291 + 729.0236 + 0 ] + /Rect [ 521.4627 + 329.5936 + 532.5827 + 341.5936 ] + /Subtype /Link + /Type /Annot >> +endobj +% 'Page1': class PDFPage +37 0 obj +% Page dictionary +<< /Annots [ 6 0 R + 7 0 R + 9 0 R + 10 0 R + 11 0 R + 12 0 R + 13 0 R + 14 0 R + 15 0 R + 16 0 R + 17 0 R + 18 0 R + 19 0 R + 20 0 R + 21 0 R + 22 0 R + 23 0 R + 24 0 R + 25 0 R + 26 0 R + 27 0 R + 28 0 R + 29 0 R + 30 0 R + 31 0 R + 32 0 R + 33 0 R + 34 0 R + 35 0 R + 36 0 R ] + /Contents 81 0 R + /MediaBox [ 0 + 0 + 595.2756 + 841.8898 ] + /Parent 80 0 R + /Resources << /Font 1 0 R + /ProcSet [ /PDF + /Text + /ImageB + /ImageC + /ImageI ] >> + /Rotate 0 + /Trans << >> + /Type /Page >> +endobj +% 'F6': class PDFType1Font +38 0 obj +% Font Helvetica-Oblique +<< /BaseFont /Helvetica-Oblique + /Encoding /WinAnsiEncoding + /Name /F6 + /Subtype /Type1 + /Type /Font >> +endobj +% 'Annot.NUMBER31': class PDFDictionary +39 0 obj +<< /A << /S /URI + /Type /Action + /URI (http://www.python.org/moin/PythonDecoratorLibrary) >> + /Border [ 0 + 0 + 0 ] + /Rect [ 219.6428 + 360.5936 + 449.1728 + 372.5936 ] + /Subtype /Link + /Type /Annot >> +endobj +% 'F7': class PDFType1Font +40 0 obj +% Font Courier-Oblique +<< /BaseFont /Courier-Oblique + /Encoding /WinAnsiEncoding + /Name /F7 + /Subtype /Type1 + /Type /Font >> +endobj +% 'Annot.NUMBER32': class PDFDictionary +41 0 obj +<< /A << /S /URI + /Type /Action + /URI (http://www.python.org/doc/2.5.2/lib/module-functools.html) >> + /Border [ 0 + 0 + 0 ] + /Rect [ 151.0486 + 127.3936 + 270.69 + 139.3936 ] + /Subtype /Link + /Type /Annot >> +endobj +% 'Page2': class PDFPage +42 0 obj +% Page dictionary +<< /Annots [ 39 0 R + 41 0 R ] + /Contents 82 0 R + /MediaBox [ 0 + 0 + 595.2756 + 841.8898 ] + /Parent 80 0 R + /Resources << /Font 1 0 R + /ProcSet [ /PDF + /Text + /ImageB + /ImageC + /ImageI ] >> + /Rotate 0 + /Trans << >> + /Type /Page >> +endobj +% 'Page3': class PDFPage +43 0 obj +% Page dictionary +<< /Contents 83 0 R + /MediaBox [ 0 + 0 + 595.2756 + 841.8898 ] + /Parent 80 0 R + /Resources << /Font 1 0 R + /ProcSet [ /PDF + /Text + /ImageB + /ImageC + /ImageI ] >> + /Rotate 0 + /Trans << >> + /Type /Page >> +endobj +% 'Page4': class PDFPage +44 0 obj +% Page dictionary +<< /Contents 84 0 R + /MediaBox [ 0 + 0 + 595.2756 + 841.8898 ] + /Parent 80 0 R + /Resources << /Font 1 0 R + /ProcSet [ /PDF + /Text + /ImageB + /ImageC + /ImageI ] >> + /Rotate 0 + /Trans << >> + /Type /Page >> +endobj +% 'Page5': class PDFPage +45 0 obj +% Page dictionary +<< /Contents 85 0 R + /MediaBox [ 0 + 0 + 595.2756 + 841.8898 ] + /Parent 80 0 R + /Resources << /Font 1 0 R + /ProcSet [ /PDF + /Text + /ImageB + /ImageC + /ImageI ] >> + /Rotate 0 + /Trans << >> + /Type /Page >> +endobj +% 'Page6': class PDFPage +46 0 obj +% Page dictionary +<< /Contents 86 0 R + /MediaBox [ 0 + 0 + 595.2756 + 841.8898 ] + /Parent 80 0 R + /Resources << /Font 1 0 R + /ProcSet [ /PDF + /Text + /ImageB + /ImageC + /ImageI ] >> + /Rotate 0 + /Trans << >> + /Type /Page >> +endobj +% 'Page7': class PDFPage +47 0 obj +% Page dictionary +<< /Contents 87 0 R + /MediaBox [ 0 + 0 + 595.2756 + 841.8898 ] + /Parent 80 0 R + /Resources << /Font 1 0 R + /ProcSet [ /PDF + /Text + /ImageB + /ImageC + /ImageI ] >> + /Rotate 0 + /Trans << >> + /Type /Page >> +endobj +% 'Page8': class PDFPage +48 0 obj +% Page dictionary +<< /Contents 88 0 R + /MediaBox [ 0 + 0 + 595.2756 + 841.8898 ] + /Parent 80 0 R + /Resources << /Font 1 0 R + /ProcSet [ /PDF + /Text + /ImageB + /ImageC + /ImageI ] >> + /Rotate 0 + /Trans << >> + /Type /Page >> +endobj +% 'Annot.NUMBER33': class PDFDictionary +49 0 obj +<< /A << /S /URI + /Type /Action + /URI (http://bugs.python.org/issue1764286) >> + /Border [ 0 + 0 + 0 ] + /Rect [ 137.6966 + 159.9936 + 180.8679 + 171.9936 ] + /Subtype /Link + /Type /Annot >> +endobj +% 'Page9': class PDFPage +50 0 obj +% Page dictionary +<< /Annots [ 49 0 R ] + /Contents 89 0 R + /MediaBox [ 0 + 0 + 595.2756 + 841.8898 ] + /Parent 80 0 R + /Resources << /Font 1 0 R + /ProcSet [ /PDF + /Text + /ImageB + /ImageC + /ImageI ] >> + /Rotate 0 + /Trans << >> + /Type /Page >> +endobj +% 'Annot.NUMBER34': class PDFDictionary +51 0 obj +<< /A << /S /URI + /Type /Action + /URI (http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/496691) >> + /Border [ 0 + 0 + 0 ] + /Rect [ 62.69291 + 339.1936 + 363.4029 + 351.1936 ] + /Subtype /Link + /Type /Annot >> +endobj +% 'Page10': class PDFPage +52 0 obj +% Page dictionary +<< /Annots [ 51 0 R ] + /Contents 90 0 R + /MediaBox [ 0 + 0 + 595.2756 + 841.8898 ] + /Parent 80 0 R + /Resources << /Font 1 0 R + /ProcSet [ /PDF + /Text + /ImageB + /ImageC + /ImageI ] >> + /Rotate 0 + /Trans << >> + /Type /Page >> +endobj +% 'Page11': class PDFPage +53 0 obj +% Page dictionary +<< /Contents 91 0 R + /MediaBox [ 0 + 0 + 595.2756 + 841.8898 ] + /Parent 80 0 R + /Resources << /Font 1 0 R + /ProcSet [ /PDF + /Text + /ImageB + /ImageC + /ImageI ] >> + /Rotate 0 + /Trans << >> + /Type /Page >> +endobj +% 'Annot.NUMBER35': class PDFDictionary +54 0 obj +<< /A << /S /URI + /Type /Action + /URI (http://www.python.org/dev/peps/pep-0362) >> + /Border [ 0 + 0 + 0 ] + /Rect [ 301.1597 + 167.7936 + 317.8397 + 179.7936 ] + /Subtype /Link + /Type /Annot >> +endobj +% 'Page12': class PDFPage +55 0 obj +% Page dictionary +<< /Annots [ 54 0 R ] + /Contents 92 0 R + /MediaBox [ 0 + 0 + 595.2756 + 841.8898 ] + /Parent 80 0 R + /Resources << /Font 1 0 R + /ProcSet [ /PDF + /Text + /ImageB + /ImageC + /ImageI ] >> + /Rotate 0 + /Trans << >> + /Type /Page >> +endobj +% 'Annot.NUMBER36': class PDFDictionary +56 0 obj +<< /A << /S /URI + /Type /Action + /URI (http://packages.python.org/distribute/) >> + /Border [ 0 + 0 + 0 ] + /Rect [ 334.9756 + 367.1936 + 381.0399 + 379.1936 ] + /Subtype /Link + /Type /Annot >> +endobj +% 'Annot.NUMBER37': class PDFDictionary +57 0 obj +<< /A << /S /URI + /Type /Action + /URI (http://docutils.sourceforge.net/) >> + /Border [ 0 + 0 + 0 ] + /Rect [ 272.2429 + 343.1936 + 308.9229 + 355.1936 ] + /Subtype /Link + /Type /Annot >> +endobj +% 'Annot.NUMBER38': class PDFDictionary +58 0 obj +<< /A << /S /URI + /Type /Action + /URI (http://pygments.org/) >> + /Border [ 0 + 0 + 0 ] + /Rect [ 328.3829 + 343.1936 + 374.5129 + 355.1936 ] + /Subtype /Link + /Type /Annot >> +endobj +% 'Annot.NUMBER39': class PDFDictionary +59 0 obj +<< /A << /S /URI + /Type /Action + /URI (http://www.python.org/dev/peps/pep-3107/) >> + /Border [ 0 + 0 + 0 ] + /Rect [ 62.69291 + 211.1936 + 157.3009 + 223.1936 ] + /Subtype /Link + /Type /Annot >> +endobj +% 'Annot.NUMBER40': class PDFDictionary +60 0 obj +<< /A << /S /URI + /Type /Action + /URI (http://www.phyast.pitt.edu/~micheles/python/documentation.html#class-decorators-and-decorator-factories) >> + /Border [ 0 + 0 + 0 ] + /Rect [ 364.2921 + 181.1936 + 531.64 + 193.1936 ] + /Subtype /Link + /Type /Annot >> +endobj +% 'Page13': class PDFPage +61 0 obj +% Page dictionary +<< /Annots [ 56 0 R + 57 0 R + 58 0 R + 59 0 R + 60 0 R ] + /Contents 93 0 R + /MediaBox [ 0 + 0 + 595.2756 + 841.8898 ] + /Parent 80 0 R + /Resources << /Font 1 0 R + /ProcSet [ /PDF + /Text + /ImageB + /ImageC + /ImageI ] >> + /Rotate 0 + /Trans << >> + /Type /Page >> +endobj +% 'Page14': class PDFPage +62 0 obj +% Page dictionary +<< /Contents 94 0 R + /MediaBox [ 0 + 0 + 595.2756 + 841.8898 ] + /Parent 80 0 R + /Resources << /Font 1 0 R + /ProcSet [ /PDF + /Text + /ImageB + /ImageC + /ImageI ] >> + /Rotate 0 + /Trans << >> + /Type /Page >> +endobj +% 'R63': class PDFCatalog +63 0 obj +% Document Root +<< /Outlines 65 0 R + /PageLabels 95 0 R + /PageMode /UseNone + /Pages 80 0 R + /Type /Catalog >> +endobj +% 'R64': class PDFInfo +64 0 obj +<< /Author (Michele Simionato) + /CreationDate (D:20100522100033-01'00') + /Keywords () + /Producer (ReportLab http://www.reportlab.com) + /Subject (\(unspecified\)) + /Title (The decorator module) >> +endobj +% 'R65': class PDFOutlines +65 0 obj +<< /Count 14 + /First 66 0 R + /Last 79 0 R + /Type /Outlines >> +endobj +% 'Outline.0': class OutlineEntryObject +66 0 obj +<< /Dest [ 37 0 R + /XYZ + 62.69291 + 311.0236 + 0 ] + /Next 67 0 R + /Parent 65 0 R + /Title (Introduction) >> +endobj +% 'Outline.1': class OutlineEntryObject +67 0 obj +<< /Dest [ 42 0 R + /XYZ + 62.69291 + 675.0236 + 0 ] + /Next 68 0 R + /Parent 65 0 R + /Prev 66 0 R + /Title (Definitions) >> +endobj +% 'Outline.2': class OutlineEntryObject +68 0 obj +<< /Dest [ 42 0 R + /XYZ + 62.69291 + 432.0236 + 0 ] + /Next 69 0 R + /Parent 65 0 R + /Prev 67 0 R + /Title (Statement of the problem) >> +endobj +% 'Outline.3': class OutlineEntryObject +69 0 obj +<< /Dest [ 43 0 R + /XYZ + 62.69291 + 427.4236 + 0 ] + /Next 70 0 R + /Parent 65 0 R + /Prev 68 0 R + /Title (The solution) >> +endobj +% 'Outline.4': class OutlineEntryObject +70 0 obj +<< /Dest [ 44 0 R + /XYZ + 62.69291 + 435.4236 + 0 ] + /Next 71 0 R + /Parent 65 0 R + /Prev 69 0 R + /Title (A trace decorator) >> +endobj +% 'Outline.5': class OutlineEntryObject +71 0 obj +<< /Dest [ 45 0 R + /XYZ + 62.69291 + 567.978 + 0 ] + /Next 72 0 R + /Parent 65 0 R + /Prev 70 0 R + /Title (decorator is a decorator) >> +endobj +% 'Outline.6': class OutlineEntryObject +72 0 obj +<< /Dest [ 45 0 R + /XYZ + 62.69291 + 153.378 + 0 ] + /Next 73 0 R + /Parent 65 0 R + /Prev 71 0 R + /Title (blocking) >> +endobj +% 'Outline.7': class OutlineEntryObject +73 0 obj +<< /Dest [ 46 0 R + /XYZ + 62.69291 + 302.6236 + 0 ] + /Next 74 0 R + /Parent 65 0 R + /Prev 72 0 R + /Title (async) >> +endobj +% 'Outline.8': class OutlineEntryObject +74 0 obj +<< /Dest [ 48 0 R + /XYZ + 62.69291 + 446.6236 + 0 ] + /Next 75 0 R + /Parent 65 0 R + /Prev 73 0 R + /Title (The FunctionMaker class) >> +endobj +% 'Outline.9': class OutlineEntryObject +75 0 obj +<< /Dest [ 50 0 R + /XYZ + 62.69291 + 449.8236 + 0 ] + /Next 76 0 R + /Parent 65 0 R + /Prev 74 0 R + /Title (Getting the source code) >> +endobj +% 'Outline.10': class OutlineEntryObject +76 0 obj +<< /Dest [ 52 0 R + /XYZ + 62.69291 + 655.8236 + 0 ] + /Next 77 0 R + /Parent 65 0 R + /Prev 75 0 R + /Title (Dealing with third party decorators) >> +endobj +% 'Outline.11': class OutlineEntryObject +77 0 obj +<< /Dest [ 53 0 R + /XYZ + 62.69291 + 263.0236 + 0 ] + /Next 78 0 R + /Parent 65 0 R + /Prev 76 0 R + /Title (Caveats and limitations) >> +endobj +% 'Outline.12': class OutlineEntryObject +78 0 obj +<< /Dest [ 61 0 R + /XYZ + 62.69291 + 426.6236 + 0 ] + /Next 79 0 R + /Parent 65 0 R + /Prev 77 0 R + /Title (Compatibility notes) >> +endobj +% 'Outline.13': class OutlineEntryObject +79 0 obj +<< /Dest [ 62 0 R + /XYZ + 62.69291 + 729.0236 + 0 ] + /Parent 65 0 R + /Prev 78 0 R + /Title (LICENCE) >> +endobj +% 'R80': class PDFPages +80 0 obj +% page tree +<< /Count 14 + /Kids [ 37 0 R + 42 0 R + 43 0 R + 44 0 R + 45 0 R + 46 0 R + 47 0 R + 48 0 R + 50 0 R + 52 0 R + 53 0 R + 55 0 R + 61 0 R + 62 0 R ] + /Type /Pages >> +endobj +% 'R81': class PDFStream +81 0 obj +% page stream +<< /Length 9103 >> +stream +1 0 0 1 0 0 cm BT /F1 12 Tf 14.4 TL ET +q +1 0 0 1 62.69291 741.0236 cm +q +BT 1 0 0 1 0 9.64 Tm 118.8249 0 Td 24 TL /F2 20 Tf 0 0 0 rg (The ) Tj /F3 20 Tf (decorator ) Tj /F2 20 Tf (module) Tj T* -118.8249 0 Td ET +Q +Q +q +1 0 0 1 62.69291 716.0236 cm +0 0 0 rg +BT /F4 10 Tf 12 TL ET +q +1 0 0 1 6 3 cm +q +0 0 0 rg +BT 1 0 0 1 0 4.82 Tm /F2 10 Tf 12 TL 36.93937 0 Td (Author:) Tj T* -36.93937 0 Td ET +Q +Q +q +1 0 0 1 91.03937 3 cm +q +0 0 0 rg +BT 1 0 0 1 0 4.82 Tm /F1 10 Tf 12 TL (Michele Simionato) Tj T* ET +Q +Q +q +Q +Q +q +1 0 0 1 62.69291 701.0236 cm +0 0 0 rg +BT /F4 10 Tf 12 TL ET +q +1 0 0 1 6 3 cm +q +0 0 0 rg +BT 1 0 0 1 0 4.82 Tm /F2 10 Tf 12 TL 39.69937 0 Td (E-mail:) Tj T* -39.69937 0 Td ET +Q +Q +q +1 0 0 1 91.03937 3 cm +q +0 0 .501961 rg +0 0 .501961 RG +BT 1 0 0 1 0 4.82 Tm /F1 10 Tf 12 TL (michele.simionato@gmail.com) Tj T* ET +Q +Q +q +Q +Q +q +1 0 0 1 62.69291 686.0236 cm +0 0 0 rg +BT /F4 10 Tf 12 TL ET +q +1 0 0 1 6 3 cm +q +0 0 0 rg +BT 1 0 0 1 0 4.82 Tm /F2 10 Tf 12 TL 33.02937 0 Td (Version:) Tj T* -33.02937 0 Td ET +Q +Q +q +1 0 0 1 91.03937 3 cm +q +0 0 0 rg +BT 1 0 0 1 0 4.82 Tm /F1 10 Tf 12 TL (3.2.0 \(2010-05-22\)) Tj T* ET +Q +Q +q +Q +Q +q +1 0 0 1 62.69291 671.0236 cm +0 0 0 rg +BT /F4 10 Tf 12 TL ET +q +1 0 0 1 6 3 cm +q +0 0 0 rg +BT 1 0 0 1 0 4.82 Tm /F2 10 Tf 12 TL 26.91937 0 Td (Requires:) Tj T* -26.91937 0 Td ET +Q +Q +q +1 0 0 1 91.03937 3 cm +q +0 0 0 rg +BT 1 0 0 1 0 4.82 Tm /F1 10 Tf 12 TL (Python 2.4+) Tj T* ET +Q +Q +q +Q +Q +q +1 0 0 1 62.69291 644.0236 cm +0 0 0 rg +BT /F4 10 Tf 12 TL ET +q +1 0 0 1 6 3 cm +q +0 0 0 rg +BT 1 0 0 1 0 16.82 Tm /F2 10 Tf 12 TL 25.25937 0 Td (Download) Tj T* 21.11 0 Td (page:) Tj T* -46.36937 0 Td ET +Q +Q +q +1 0 0 1 91.03937 15 cm +q +0 0 .501961 rg +0 0 .501961 RG +BT 1 0 0 1 0 4.82 Tm /F1 10 Tf 12 TL (http://pypi.python.org/pypi/decorator/3.2.0) Tj T* ET +Q +Q +q +Q +Q +q +1 0 0 1 62.69291 629.0236 cm +0 0 0 rg +BT /F4 10 Tf 12 TL ET +q +1 0 0 1 6 3 cm +q +0 0 0 rg +BT 1 0 0 1 0 4.82 Tm /F2 10 Tf 12 TL 16.91937 0 Td (Installation:) Tj T* -16.91937 0 Td ET +Q +Q +q +1 0 0 1 91.03937 3 cm +q +0 0 0 rg +BT 1 0 0 1 0 5.71 Tm /F5 10 Tf 12 TL (easy_install decorator) Tj T* ET +Q +Q +q +Q +Q +q +1 0 0 1 62.69291 614.0236 cm +0 0 0 rg +BT /F4 10 Tf 12 TL ET +q +1 0 0 1 6 3 cm +q +0 0 0 rg +BT 1 0 0 1 0 4.82 Tm /F2 10 Tf 12 TL 32.46937 0 Td (License:) Tj T* -32.46937 0 Td ET +Q +Q +q +1 0 0 1 91.03937 3 cm +q +0 0 0 rg +BT 1 0 0 1 0 4.82 Tm /F1 10 Tf 12 TL (BSD license) Tj T* ET +Q +Q +q +Q +Q +q +1 0 0 1 62.69291 581.0236 cm +q +BT 1 0 0 1 0 8.435 Tm 21 TL /F2 17.5 Tf 0 0 0 rg (Contents) Tj T* ET +Q +Q +q +1 0 0 1 62.69291 323.0236 cm +0 0 0 rg +BT /F4 10 Tf 12 TL ET +q +1 0 0 1 0 237 cm +q +BT 1 0 0 1 0 4.82 Tm 12 TL /F2 10 Tf 0 0 .501961 rg (Introduction) Tj T* ET +Q +Q +q +1 0 0 1 397.8898 237 cm +q +0 0 .501961 rg +0 0 .501961 RG +BT 1 0 0 1 0 4.82 Tm /F2 10 Tf 12 TL 66.44 0 Td (1) Tj T* -66.44 0 Td ET +Q +Q +q +1 0 0 1 0 219 cm +q +BT 1 0 0 1 0 4.82 Tm 12 TL /F2 10 Tf 0 0 .501961 rg (Definitions) Tj T* ET +Q +Q +q +1 0 0 1 397.8898 219 cm +q +0 0 .501961 rg +0 0 .501961 RG +BT 1 0 0 1 0 4.82 Tm /F2 10 Tf 12 TL 66.44 0 Td (2) Tj T* -66.44 0 Td ET +Q +Q +q +1 0 0 1 0 201 cm +q +BT 1 0 0 1 0 4.82 Tm 12 TL /F2 10 Tf 0 0 .501961 rg (Statement of the problem) Tj T* ET +Q +Q +q +1 0 0 1 397.8898 201 cm +q +0 0 .501961 rg +0 0 .501961 RG +BT 1 0 0 1 0 4.82 Tm /F2 10 Tf 12 TL 66.44 0 Td (2) Tj T* -66.44 0 Td ET +Q +Q +q +1 0 0 1 0 183 cm +q +BT 1 0 0 1 0 4.82 Tm 12 TL /F2 10 Tf 0 0 .501961 rg (The solution) Tj T* ET +Q +Q +q +1 0 0 1 397.8898 183 cm +q +0 0 .501961 rg +0 0 .501961 RG +BT 1 0 0 1 0 4.82 Tm /F2 10 Tf 12 TL 66.44 0 Td (3) Tj T* -66.44 0 Td ET +Q +Q +q +1 0 0 1 0 165 cm +q +BT 1 0 0 1 0 4.82 Tm 12 TL /F2 10 Tf 0 0 .501961 rg (A ) Tj /F3 10 Tf (trace ) Tj /F2 10 Tf (decorator) Tj T* ET +Q +Q +q +1 0 0 1 397.8898 165 cm +q +0 0 .501961 rg +0 0 .501961 RG +BT 1 0 0 1 0 4.82 Tm /F2 10 Tf 12 TL 66.44 0 Td (4) Tj T* -66.44 0 Td ET +Q +Q +q +1 0 0 1 0 147 cm +q +BT 1 0 0 1 0 4.82 Tm 12 TL /F3 10 Tf 0 0 .501961 rg (decorator ) Tj /F2 10 Tf (is a decorator) Tj T* ET +Q +Q +q +1 0 0 1 397.8898 147 cm +q +0 0 .501961 rg +0 0 .501961 RG +BT 1 0 0 1 0 4.82 Tm /F2 10 Tf 12 TL 66.44 0 Td (5) Tj T* -66.44 0 Td ET +Q +Q +q +1 0 0 1 0 129 cm +q +BT 1 0 0 1 0 4.82 Tm 12 TL /F3 10 Tf 0 0 .501961 rg (blocking) Tj T* ET +Q +Q +q +1 0 0 1 397.8898 129 cm +q +0 0 .501961 rg +0 0 .501961 RG +BT 1 0 0 1 0 4.82 Tm /F2 10 Tf 12 TL 66.44 0 Td (5) Tj T* -66.44 0 Td ET +Q +Q +q +1 0 0 1 0 111 cm +q +BT 1 0 0 1 0 4.82 Tm 12 TL /F3 10 Tf 0 0 .501961 rg (async) Tj T* ET +Q +Q +q +1 0 0 1 397.8898 111 cm +q +0 0 .501961 rg +0 0 .501961 RG +BT 1 0 0 1 0 4.82 Tm /F2 10 Tf 12 TL 66.44 0 Td (6) Tj T* -66.44 0 Td ET +Q +Q +q +1 0 0 1 0 93 cm +q +BT 1 0 0 1 0 4.82 Tm 12 TL /F2 10 Tf 0 0 .501961 rg (The ) Tj /F3 10 Tf (FunctionMaker ) Tj /F2 10 Tf (class) Tj T* ET +Q +Q +q +1 0 0 1 397.8898 93 cm +q +0 0 .501961 rg +0 0 .501961 RG +BT 1 0 0 1 0 4.82 Tm /F2 10 Tf 12 TL 66.44 0 Td (8) Tj T* -66.44 0 Td ET +Q +Q +q +1 0 0 1 0 75 cm +q +BT 1 0 0 1 0 4.82 Tm 12 TL /F2 10 Tf 0 0 .501961 rg (Getting the source code) Tj T* ET +Q +Q +q +1 0 0 1 397.8898 75 cm +q +0 0 .501961 rg +0 0 .501961 RG +BT 1 0 0 1 0 4.82 Tm /F2 10 Tf 12 TL 66.44 0 Td (9) Tj T* -66.44 0 Td ET +Q +Q +q +1 0 0 1 0 57 cm +q +BT 1 0 0 1 0 4.82 Tm 12 TL /F2 10 Tf 0 0 .501961 rg (Dealing with third party decorators) Tj T* ET +Q +Q +q +1 0 0 1 397.8898 57 cm +q +0 0 .501961 rg +0 0 .501961 RG +BT 1 0 0 1 0 4.82 Tm /F2 10 Tf 12 TL 60.88 0 Td (10) Tj T* -60.88 0 Td ET +Q +Q +q +1 0 0 1 0 39 cm +q +BT 1 0 0 1 0 4.82 Tm 12 TL /F2 10 Tf 0 0 .501961 rg (Caveats and limitations) Tj T* ET +Q +Q +q +1 0 0 1 397.8898 39 cm +q +0 0 .501961 rg +0 0 .501961 RG +BT 1 0 0 1 0 4.82 Tm /F2 10 Tf 12 TL 60.88 0 Td (11) Tj T* -60.88 0 Td ET +Q +Q +q +1 0 0 1 0 21 cm +q +BT 1 0 0 1 0 4.82 Tm 12 TL /F2 10 Tf 0 0 .501961 rg (Compatibility notes) Tj T* ET +Q +Q +q +1 0 0 1 397.8898 21 cm +q +0 0 .501961 rg +0 0 .501961 RG +BT 1 0 0 1 0 4.82 Tm /F2 10 Tf 12 TL 60.88 0 Td (13) Tj T* -60.88 0 Td ET +Q +Q +q +1 0 0 1 0 3 cm +q +BT 1 0 0 1 0 4.82 Tm 12 TL /F2 10 Tf 0 0 .501961 rg (LICENCE) Tj T* ET +Q +Q +q +1 0 0 1 397.8898 3 cm +q +0 0 .501961 rg +0 0 .501961 RG +BT 1 0 0 1 0 4.82 Tm /F2 10 Tf 12 TL 60.88 0 Td (14) Tj T* -60.88 0 Td ET +Q +Q +q +Q +Q +q +1 0 0 1 62.69291 290.0236 cm +q +BT 1 0 0 1 0 8.435 Tm 21 TL /F2 17.5 Tf 0 0 0 rg (Introduction) Tj T* ET +Q +Q +q +1 0 0 1 62.69291 224.0236 cm +q +0 0 0 rg +BT 1 0 0 1 0 52.82 Tm /F1 10 Tf 12 TL 3.995366 Tw (Python decorators are an interesting example of why syntactic sugar matters. In principle, their) Tj T* 0 Tw .151235 Tw (introduction in Python 2.4 changed nothing, since they do not provide any new functionality which was not) Tj T* 0 Tw 2.238555 Tw (already present in the language. In practice, their introduction has significantly changed the way we) Tj T* 0 Tw .098409 Tw (structure our programs in Python. I believe the change is for the best, and that decorators are a great idea) Tj T* 0 Tw (since:) Tj T* ET +Q +Q +q +1 0 0 1 62.69291 218.0236 cm +Q +q +1 0 0 1 62.69291 218.0236 cm +Q +q +1 0 0 1 62.69291 200.0236 cm +0 0 0 rg +BT /F4 10 Tf 12 TL ET +q +1 0 0 1 6 3 cm +q +0 0 0 rg +BT 1 0 0 1 0 4.82 Tm /F1 10 Tf 12 TL 10.5 0 Td (\177) Tj T* -10.5 0 Td ET +Q +Q +q +1 0 0 1 23 3 cm +q +0 0 0 rg +BT 1 0 0 1 0 4.82 Tm /F1 10 Tf 12 TL (decorators help reducing boilerplate code;) Tj T* ET +Q +Q +q +Q +Q +q +1 0 0 1 62.69291 200.0236 cm +Q +q +1 0 0 1 62.69291 200.0236 cm +Q +q +1 0 0 1 62.69291 182.0236 cm +0 0 0 rg +BT /F4 10 Tf 12 TL ET +q +1 0 0 1 6 3 cm +q +0 0 0 rg +BT 1 0 0 1 0 4.82 Tm /F1 10 Tf 12 TL 10.5 0 Td (\177) Tj T* -10.5 0 Td ET +Q +Q +q +1 0 0 1 23 3 cm +q +0 0 0 rg +BT 1 0 0 1 0 4.82 Tm /F1 10 Tf 12 TL (decorators help separation of concerns;) Tj T* ET +Q +Q +q +Q +Q +q +1 0 0 1 62.69291 182.0236 cm +Q +q +1 0 0 1 62.69291 182.0236 cm +Q +q +1 0 0 1 62.69291 164.0236 cm +0 0 0 rg +BT /F4 10 Tf 12 TL ET +q +1 0 0 1 6 3 cm +q +0 0 0 rg +BT 1 0 0 1 0 4.82 Tm /F1 10 Tf 12 TL 10.5 0 Td (\177) Tj T* -10.5 0 Td ET +Q +Q +q +1 0 0 1 23 3 cm +q +0 0 0 rg +BT 1 0 0 1 0 4.82 Tm /F1 10 Tf 12 TL (decorators enhance readability and maintenability;) Tj T* ET +Q +Q +q +Q +Q +q +1 0 0 1 62.69291 164.0236 cm +Q +q +1 0 0 1 62.69291 164.0236 cm +Q +q +1 0 0 1 62.69291 146.0236 cm +0 0 0 rg +BT /F4 10 Tf 12 TL ET +q +1 0 0 1 6 3 cm +q +0 0 0 rg +BT 1 0 0 1 0 4.82 Tm /F1 10 Tf 12 TL 10.5 0 Td (\177) Tj T* -10.5 0 Td ET +Q +Q +q +1 0 0 1 23 3 cm +q +0 0 0 rg +BT 1 0 0 1 0 4.82 Tm /F1 10 Tf 12 TL (decorators are explicit.) Tj T* ET +Q +Q +q +Q +Q +q +1 0 0 1 62.69291 146.0236 cm +Q +q +1 0 0 1 62.69291 146.0236 cm +Q +q +1 0 0 1 62.69291 104.0236 cm +q +0 0 0 rg +BT 1 0 0 1 0 28.82 Tm /F1 10 Tf 12 TL .848876 Tw (Still, as of now, writing custom decorators correctly requires some experience and it is not as easy as it) Tj T* 0 Tw 1.049269 Tw (could be. For instance, typical implementations of decorators involve nested functions, and we all know) Tj T* 0 Tw (that flat is better than nested.) Tj T* ET +Q +Q + +endstream + +endobj +% 'R82': class PDFStream +82 0 obj +% page stream +<< /Length 7636 >> +stream +1 0 0 1 0 0 cm BT /F1 12 Tf 14.4 TL ET +q +1 0 0 1 62.69291 717.0236 cm +q +BT 1 0 0 1 0 40.82 Tm 1.093735 Tw 12 TL /F1 10 Tf 0 0 0 rg (The aim of the ) Tj /F5 10 Tf (decorator ) Tj /F1 10 Tf (module it to simplify the usage of decorators for the average programmer,) Tj T* 0 Tw 2.456136 Tw (and to popularize decorators by showing various non-trivial examples. Of course, as all techniques,) Tj T* 0 Tw 2.234987 Tw (decorators can be abused \(I have seen that\) and you should not try to solve every problem with a) Tj T* 0 Tw (decorator, just because you can.) Tj T* ET +Q +Q +q +1 0 0 1 62.69291 687.0236 cm +q +BT 1 0 0 1 0 16.82 Tm .13561 Tw 12 TL /F1 10 Tf 0 0 0 rg (You may find the source code for all the examples discussed here in the ) Tj /F5 10 Tf (documentation.py ) Tj /F1 10 Tf (file, which) Tj T* 0 Tw (contains this documentation in the form of doctests.) Tj T* ET +Q +Q +q +1 0 0 1 62.69291 654.0236 cm +q +BT 1 0 0 1 0 8.435 Tm 21 TL /F2 17.5 Tf 0 0 0 rg (Definitions) Tj T* ET +Q +Q +q +1 0 0 1 62.69291 612.0236 cm +q +0 0 0 rg +BT 1 0 0 1 0 28.82 Tm /F1 10 Tf 12 TL 2.37561 Tw (Technically speaking, any Python object which can be called with one argument can be used as a) Tj T* 0 Tw .472339 Tw (decorator. However, this definition is somewhat too large to be really useful. It is more convenient to split) Tj T* 0 Tw (the generic class of decorators in two subclasses:) Tj T* ET +Q +Q +q +1 0 0 1 62.69291 606.0236 cm +Q +q +1 0 0 1 62.69291 606.0236 cm +Q +q +1 0 0 1 62.69291 576.0236 cm +0 0 0 rg +BT /F4 10 Tf 12 TL ET +q +1 0 0 1 6 15 cm +q +0 0 0 rg +BT 1 0 0 1 0 4.82 Tm /F1 10 Tf 12 TL 10.5 0 Td (\177) Tj T* -10.5 0 Td ET +Q +Q +q +1 0 0 1 23 3 cm +q +BT 1 0 0 1 0 16.82 Tm 2.68748 Tw 12 TL /F6 10 Tf 0 0 0 rg (signature-preserving ) Tj /F1 10 Tf (decorators, i.e. callable objects taking a function as input and returning a) Tj T* 0 Tw (function ) Tj /F6 10 Tf (with the same signature ) Tj /F1 10 Tf (as output;) Tj T* ET +Q +Q +q +Q +Q +q +1 0 0 1 62.69291 576.0236 cm +Q +q +1 0 0 1 62.69291 576.0236 cm +Q +q +1 0 0 1 62.69291 546.0236 cm +0 0 0 rg +BT /F4 10 Tf 12 TL ET +q +1 0 0 1 6 15 cm +q +0 0 0 rg +BT 1 0 0 1 0 4.82 Tm /F1 10 Tf 12 TL 10.5 0 Td (\177) Tj T* -10.5 0 Td ET +Q +Q +q +1 0 0 1 23 3 cm +q +BT 1 0 0 1 0 16.82 Tm 1.43498 Tw 12 TL /F6 10 Tf 0 0 0 rg (signature-changing ) Tj /F1 10 Tf (decorators, i.e. decorators that change the signature of their input function, or) Tj T* 0 Tw (decorators returning non-callable objects.) Tj T* ET +Q +Q +q +Q +Q +q +1 0 0 1 62.69291 546.0236 cm +Q +q +1 0 0 1 62.69291 546.0236 cm +Q +q +1 0 0 1 62.69291 504.0236 cm +q +BT 1 0 0 1 0 28.82 Tm 2.832706 Tw 12 TL /F1 10 Tf 0 0 0 rg (Signature-changing decorators have their use: for instance the builtin classes ) Tj /F5 10 Tf (staticmethod ) Tj /F1 10 Tf (and) Tj T* 0 Tw 1.506651 Tw /F5 10 Tf (classmethod ) Tj /F1 10 Tf (are in this group, since they take functions and return descriptor objects which are not) Tj T* 0 Tw (functions, nor callables.) Tj T* ET +Q +Q +q +1 0 0 1 62.69291 474.0236 cm +q +0 0 0 rg +BT 1 0 0 1 0 16.82 Tm /F1 10 Tf 12 TL 1.735814 Tw (However, signature-preserving decorators are more common and easier to reason about; in particular) Tj T* 0 Tw (signature-preserving decorators can be composed together whereas other decorators in general cannot.) Tj T* ET +Q +Q +q +1 0 0 1 62.69291 444.0236 cm +q +0 0 0 rg +BT 1 0 0 1 0 16.82 Tm /F1 10 Tf 12 TL .494983 Tw (Writing signature-preserving decorators from scratch is not that obvious, especially if one wants to define) Tj T* 0 Tw (proper decorators that can accept functions with any signature. A simple example will clarify the issue.) Tj T* ET +Q +Q +q +1 0 0 1 62.69291 411.0236 cm +q +BT 1 0 0 1 0 8.435 Tm 21 TL /F2 17.5 Tf 0 0 0 rg (Statement of the problem) Tj T* ET +Q +Q +q +1 0 0 1 62.69291 333.0236 cm +q +BT 1 0 0 1 0 64.82 Tm .351235 Tw 12 TL /F1 10 Tf 0 0 0 rg (A very common use case for decorators is the memoization of functions. A ) Tj /F5 10 Tf (memoize ) Tj /F1 10 Tf (decorator works by) Tj T* 0 Tw .871988 Tw (caching the result of the function call in a dictionary, so that the next time the function is called with the) Tj T* 0 Tw 2.350651 Tw (same input parameters the result is retrieved from the cache and not recomputed. There are many) Tj T* 0 Tw 2.92247 Tw (implementations of ) Tj /F5 10 Tf (memoize ) Tj /F1 10 Tf (in ) Tj 0 0 .501961 rg (http://www.python.org/moin/PythonDecoratorLibrary) Tj 0 0 0 rg (, but they do not) Tj T* 0 Tw 2.683984 Tw (preserve the signature. A simple implementation could be the following \(notice that in general it is) Tj T* 0 Tw (impossible to memoize correctly something that depends on non-hashable arguments\):) Tj T* ET +Q +Q +q +1 0 0 1 62.69291 143.8236 cm +q +q +1 0 0 1 0 0 cm +q +1 0 0 1 6.6 6.6 cm +q +.662745 .662745 .662745 RG +.5 w +.960784 .960784 .862745 rg +n -6 -6 468.6898 180 re B* +Q +q +BT 1 0 0 1 0 161.71 Tm 12 TL /F3 10 Tf 0 .501961 0 rg (def) Tj /F5 10 Tf 0 0 0 rg ( ) Tj 0 0 1 rg (memoize_uw) Tj 0 0 0 rg (\() Tj (func) Tj (\):) Tj T* ( ) Tj (func) Tj .4 .4 .4 rg (.) Tj 0 0 0 rg (cache) Tj ( ) Tj .4 .4 .4 rg (=) Tj 0 0 0 rg ( ) Tj ({}) Tj T* ( ) Tj /F3 10 Tf 0 .501961 0 rg (def) Tj /F5 10 Tf 0 0 0 rg ( ) Tj 0 0 1 rg (memoize) Tj 0 0 0 rg (\() Tj .4 .4 .4 rg (*) Tj 0 0 0 rg (args) Tj (,) Tj ( ) Tj .4 .4 .4 rg (**) Tj 0 0 0 rg (kw) Tj (\):) Tj T* ( ) Tj /F3 10 Tf 0 .501961 0 rg (if) Tj /F5 10 Tf 0 0 0 rg ( ) Tj (kw) Tj (:) Tj ( ) Tj /F7 10 Tf .25098 .501961 .501961 rg (# frozenset is used to ensure hashability) Tj /F5 10 Tf 0 0 0 rg T* ( ) Tj (key) Tj ( ) Tj .4 .4 .4 rg (=) Tj 0 0 0 rg ( ) Tj (args) Tj (,) Tj ( ) Tj (frozenset) Tj (\() Tj (kw) Tj .4 .4 .4 rg (.) Tj 0 0 0 rg (iteritems) Tj (\(\)\)) Tj T* ( ) Tj /F3 10 Tf 0 .501961 0 rg (else) Tj /F5 10 Tf 0 0 0 rg (:) Tj T* ( ) Tj (key) Tj ( ) Tj .4 .4 .4 rg (=) Tj 0 0 0 rg ( ) Tj (args) Tj T* ( ) Tj (cache) Tj ( ) Tj .4 .4 .4 rg (=) Tj 0 0 0 rg ( ) Tj (func) Tj .4 .4 .4 rg (.) Tj 0 0 0 rg (cache) Tj T* ( ) Tj /F3 10 Tf 0 .501961 0 rg (if) Tj /F5 10 Tf 0 0 0 rg ( ) Tj (key) Tj ( ) Tj /F3 10 Tf .666667 .133333 1 rg (in) Tj /F5 10 Tf 0 0 0 rg ( ) Tj (cache) Tj (:) Tj T* ( ) Tj /F3 10 Tf 0 .501961 0 rg (return) Tj /F5 10 Tf 0 0 0 rg ( ) Tj (cache) Tj ([) Tj (key) Tj (]) Tj T* ( ) Tj /F3 10 Tf 0 .501961 0 rg (else) Tj /F5 10 Tf 0 0 0 rg (:) Tj T* ( ) Tj (cache) Tj ([) Tj (key) Tj (]) Tj ( ) Tj .4 .4 .4 rg (=) Tj 0 0 0 rg ( ) Tj (result) Tj ( ) Tj .4 .4 .4 rg (=) Tj 0 0 0 rg ( ) Tj (func) Tj (\() Tj .4 .4 .4 rg (*) Tj 0 0 0 rg (args) Tj (,) Tj ( ) Tj .4 .4 .4 rg (**) Tj 0 0 0 rg (kw) Tj (\)) Tj T* ( ) Tj /F3 10 Tf 0 .501961 0 rg (return) Tj /F5 10 Tf 0 0 0 rg ( ) Tj (result) Tj T* ( ) Tj /F3 10 Tf 0 .501961 0 rg (return) Tj /F5 10 Tf 0 0 0 rg ( ) Tj (functools) Tj .4 .4 .4 rg (.) Tj 0 0 0 rg (update_wrapper) Tj (\() Tj (memoize) Tj (,) Tj ( ) Tj (func) Tj (\)) Tj T* ET +Q +Q +Q +Q +Q +q +1 0 0 1 62.69291 87.82362 cm +q +BT 1 0 0 1 0 40.82 Tm 1.801412 Tw 12 TL /F1 10 Tf 0 0 0 rg (Here we used the ) Tj 0 0 .501961 rg (functools.update_wrapper ) Tj 0 0 0 rg (utility, which has been added in Python 2.5 expressly to) Tj T* 0 Tw .91686 Tw (simplify the definition of decorators \(in older versions of Python you need to copy the function attributes) Tj T* 0 Tw .580814 Tw /F5 10 Tf (__name__) Tj /F1 10 Tf (, ) Tj /F5 10 Tf (__doc__) Tj /F1 10 Tf (, ) Tj /F5 10 Tf (__module__ ) Tj /F1 10 Tf (and ) Tj /F5 10 Tf (__dict__ ) Tj /F1 10 Tf (from the original function to the decorated function) Tj T* 0 Tw (by hand\).) Tj T* ET +Q +Q + +endstream + +endobj +% 'R83': class PDFStream +83 0 obj +% page stream +<< /Length 7980 >> +stream +1 0 0 1 0 0 cm BT /F1 12 Tf 14.4 TL ET +q +1 0 0 1 62.69291 729.0236 cm +q +BT 1 0 0 1 0 28.82 Tm 2.517126 Tw 12 TL /F1 10 Tf 0 0 0 rg (The implementation above works in the sense that the decorator can accept functions with generic) Tj T* 0 Tw 1.233615 Tw (signatures; unfortunately this implementation does ) Tj /F6 10 Tf (not ) Tj /F1 10 Tf (define a signature-preserving decorator, since in) Tj T* 0 Tw (general ) Tj /F5 10 Tf (memoize_uw ) Tj /F1 10 Tf (returns a function with a ) Tj /F6 10 Tf (different signature ) Tj /F1 10 Tf (from the original function.) Tj T* ET +Q +Q +q +1 0 0 1 62.69291 711.0236 cm +q +0 0 0 rg +BT 1 0 0 1 0 4.82 Tm /F1 10 Tf 12 TL (Consider for instance the following case:) Tj T* ET +Q +Q +q +1 0 0 1 62.69291 641.8236 cm +q +q +1 0 0 1 0 0 cm +q +1 0 0 1 6.6 6.6 cm +q +.662745 .662745 .662745 RG +.5 w +.960784 .960784 .862745 rg +n -6 -6 468.6898 60 re B* +Q +q +BT 1 0 0 1 0 41.71 Tm 12 TL /F5 10 Tf .4 .4 .4 rg (>) Tj (>) Tj (>) Tj 0 0 0 rg ( ) Tj .666667 .133333 1 rg (@memoize_uw) Tj 0 0 0 rg T* .4 .4 .4 rg (...) Tj 0 0 0 rg ( ) Tj /F3 10 Tf 0 .501961 0 rg (def) Tj /F5 10 Tf 0 0 0 rg ( ) Tj 0 0 1 rg (f1) Tj 0 0 0 rg (\() Tj (x) Tj (\):) Tj T* .4 .4 .4 rg (...) Tj 0 0 0 rg ( ) Tj (time) Tj .4 .4 .4 rg (.) Tj 0 0 0 rg (sleep) Tj (\() Tj .4 .4 .4 rg (1) Tj 0 0 0 rg (\)) Tj ( ) Tj /F7 10 Tf .25098 .501961 .501961 rg (# simulate some long computation) Tj /F5 10 Tf 0 0 0 rg T* .4 .4 .4 rg (...) Tj 0 0 0 rg ( ) Tj /F3 10 Tf 0 .501961 0 rg (return) Tj /F5 10 Tf 0 0 0 rg ( ) Tj (x) Tj T* ET +Q +Q +Q +Q +Q +q +1 0 0 1 62.69291 609.8236 cm +q +BT 1 0 0 1 0 16.82 Tm .26311 Tw 12 TL /F1 10 Tf 0 0 0 rg (Here the original function takes a single argument named ) Tj /F5 10 Tf (x) Tj /F1 10 Tf (, but the decorated function takes any number) Tj T* 0 Tw (of arguments and keyword arguments:) Tj T* ET +Q +Q +q +1 0 0 1 62.69291 552.6236 cm +q +q +1 0 0 1 0 0 cm +q +1 0 0 1 6.6 6.6 cm +q +.662745 .662745 .662745 RG +.5 w +.960784 .960784 .862745 rg +n -6 -6 468.6898 48 re B* +Q +q +BT 1 0 0 1 0 29.71 Tm 12 TL /F5 10 Tf .4 .4 .4 rg (>) Tj (>) Tj (>) Tj 0 0 0 rg ( ) Tj /F3 10 Tf 0 .501961 0 rg (from) Tj /F5 10 Tf 0 0 0 rg ( ) Tj /F3 10 Tf 0 0 1 rg (inspect) Tj /F5 10 Tf 0 0 0 rg ( ) Tj /F3 10 Tf 0 .501961 0 rg (import) Tj /F5 10 Tf 0 0 0 rg ( ) Tj (getargspec) Tj T* .4 .4 .4 rg (>) Tj (>) Tj (>) Tj 0 0 0 rg ( ) Tj /F3 10 Tf 0 .501961 0 rg (print) Tj /F5 10 Tf 0 0 0 rg (\() Tj (getargspec) Tj (\() Tj (f1) Tj (\)\)) Tj T* (ArgSpec) Tj (\() Tj (args) Tj .4 .4 .4 rg (=) Tj 0 0 0 rg ([],) Tj ( ) Tj (varargs) Tj .4 .4 .4 rg (=) Tj .729412 .129412 .129412 rg ('args') Tj 0 0 0 rg (,) Tj ( ) Tj (keywords) Tj .4 .4 .4 rg (=) Tj .729412 .129412 .129412 rg ('kw') Tj 0 0 0 rg (,) Tj ( ) Tj (defaults) Tj .4 .4 .4 rg (=) Tj 0 .501961 0 rg (None) Tj 0 0 0 rg (\)) Tj T* ET +Q +Q +Q +Q +Q +q +1 0 0 1 62.69291 508.6236 cm +q +BT 1 0 0 1 0 28.82 Tm .411235 Tw 12 TL /F1 10 Tf 0 0 0 rg (This means that introspection tools such as pydoc will give wrong informations about the signature of ) Tj /F5 10 Tf (f1) Tj /F1 10 Tf (.) Tj T* 0 Tw .161654 Tw (This is pretty bad: pydoc will tell you that the function accepts a generic signature ) Tj /F5 10 Tf (*args) Tj /F1 10 Tf (, ) Tj /F5 10 Tf (**kw) Tj /F1 10 Tf (, but when) Tj T* 0 Tw (you try to call the function with more than an argument, you will get an error:) Tj T* ET +Q +Q +q +1 0 0 1 62.69291 439.4236 cm +q +q +1 0 0 1 0 0 cm +q +1 0 0 1 6.6 6.6 cm +q +.662745 .662745 .662745 RG +.5 w +.960784 .960784 .862745 rg +n -6 -6 468.6898 60 re B* +Q +q +BT 1 0 0 1 0 41.71 Tm 12 TL /F5 10 Tf .4 .4 .4 rg (>) Tj (>) Tj (>) Tj 0 0 0 rg ( ) Tj (f1) Tj (\() Tj .4 .4 .4 rg (0) Tj 0 0 0 rg (,) Tj ( ) Tj .4 .4 .4 rg (1) Tj 0 0 0 rg (\)) Tj T* (Traceback) Tj ( ) Tj (\() Tj (most) Tj ( ) Tj (recent) Tj ( ) Tj (call) Tj ( ) Tj (last) Tj (\):) Tj T* ( ) Tj .4 .4 .4 rg (...) Tj 0 0 0 rg T* /F3 10 Tf .823529 .254902 .227451 rg (TypeError) Tj /F5 10 Tf 0 0 0 rg (:) Tj ( ) Tj (f1) Tj (\(\)) Tj ( ) Tj (takes) Tj ( ) Tj (exactly) Tj ( ) Tj .4 .4 .4 rg (1) Tj 0 0 0 rg ( ) Tj (positional) Tj ( ) Tj (argument) Tj ( ) Tj (\() Tj .4 .4 .4 rg (2) Tj 0 0 0 rg ( ) Tj (given) Tj (\)) Tj T* ET +Q +Q +Q +Q +Q +q +1 0 0 1 62.69291 406.4236 cm +q +BT 1 0 0 1 0 8.435 Tm 21 TL /F2 17.5 Tf 0 0 0 rg (The solution) Tj T* ET +Q +Q +q +1 0 0 1 62.69291 364.4236 cm +q +BT 1 0 0 1 0 28.82 Tm 3.313984 Tw 12 TL /F1 10 Tf 0 0 0 rg (The solution is to provide a generic factory of generators, which hides the complexity of making) Tj T* 0 Tw 3.362976 Tw (signature-preserving decorators from the application programmer. The ) Tj /F5 10 Tf (decorator ) Tj /F1 10 Tf (function in the) Tj T* 0 Tw /F5 10 Tf (decorator ) Tj /F1 10 Tf (module is such a factory:) Tj T* ET +Q +Q +q +1 0 0 1 62.69291 331.2236 cm +q +q +1 0 0 1 0 0 cm +q +1 0 0 1 6.6 6.6 cm +q +.662745 .662745 .662745 RG +.5 w +.960784 .960784 .862745 rg +n -6 -6 468.6898 24 re B* +Q +q +BT 1 0 0 1 0 5.71 Tm 12 TL /F5 10 Tf .4 .4 .4 rg (>) Tj (>) Tj (>) Tj 0 0 0 rg ( ) Tj /F3 10 Tf 0 .501961 0 rg (from) Tj /F5 10 Tf 0 0 0 rg ( ) Tj /F3 10 Tf 0 0 1 rg (decorator) Tj /F5 10 Tf 0 0 0 rg ( ) Tj /F3 10 Tf 0 .501961 0 rg (import) Tj /F5 10 Tf 0 0 0 rg ( ) Tj (decorator) Tj T* ET +Q +Q +Q +Q +Q +q +1 0 0 1 62.69291 275.2236 cm +q +BT 1 0 0 1 0 40.82 Tm 1.716412 Tw 12 TL /F5 10 Tf 0 0 0 rg (decorator ) Tj /F1 10 Tf (takes two arguments, a caller function describing the functionality of the decorator and a) Tj T* 0 Tw .821984 Tw (function to be decorated; it returns the decorated function. The caller function must have signature ) Tj /F5 10 Tf (\(f,) Tj T* 0 Tw .65061 Tw (*args, **kw\) ) Tj /F1 10 Tf (and it must call the original function ) Tj /F5 10 Tf (f ) Tj /F1 10 Tf (with arguments ) Tj /F5 10 Tf (args ) Tj /F1 10 Tf (and ) Tj /F5 10 Tf (kw) Tj /F1 10 Tf (, implementing the) Tj T* 0 Tw (wanted capability, i.e. memoization in this case:) Tj T* ET +Q +Q +q +1 0 0 1 62.69291 122.0236 cm +q +q +1 0 0 1 0 0 cm +q +1 0 0 1 6.6 6.6 cm +q +.662745 .662745 .662745 RG +.5 w +.960784 .960784 .862745 rg +n -6 -6 468.6898 144 re B* +Q +q +BT 1 0 0 1 0 125.71 Tm 12 TL /F3 10 Tf 0 .501961 0 rg (def) Tj /F5 10 Tf 0 0 0 rg ( ) Tj 0 0 1 rg (_memoize) Tj 0 0 0 rg (\() Tj (func) Tj (,) Tj ( ) Tj .4 .4 .4 rg (*) Tj 0 0 0 rg (args) Tj (,) Tj ( ) Tj .4 .4 .4 rg (**) Tj 0 0 0 rg (kw) Tj (\):) Tj T* ( ) Tj /F3 10 Tf 0 .501961 0 rg (if) Tj /F5 10 Tf 0 0 0 rg ( ) Tj (kw) Tj (:) Tj ( ) Tj /F7 10 Tf .25098 .501961 .501961 rg (# frozenset is used to ensure hashability) Tj /F5 10 Tf 0 0 0 rg T* ( ) Tj (key) Tj ( ) Tj .4 .4 .4 rg (=) Tj 0 0 0 rg ( ) Tj (args) Tj (,) Tj ( ) Tj (frozenset) Tj (\() Tj (kw) Tj .4 .4 .4 rg (.) Tj 0 0 0 rg (iteritems) Tj (\(\)\)) Tj T* ( ) Tj /F3 10 Tf 0 .501961 0 rg (else) Tj /F5 10 Tf 0 0 0 rg (:) Tj T* ( ) Tj (key) Tj ( ) Tj .4 .4 .4 rg (=) Tj 0 0 0 rg ( ) Tj (args) Tj T* ( ) Tj (cache) Tj ( ) Tj .4 .4 .4 rg (=) Tj 0 0 0 rg ( ) Tj (func) Tj .4 .4 .4 rg (.) Tj 0 0 0 rg (cache) Tj ( ) Tj /F7 10 Tf .25098 .501961 .501961 rg (# attributed added by memoize) Tj /F5 10 Tf 0 0 0 rg T* ( ) Tj /F3 10 Tf 0 .501961 0 rg (if) Tj /F5 10 Tf 0 0 0 rg ( ) Tj (key) Tj ( ) Tj /F3 10 Tf .666667 .133333 1 rg (in) Tj /F5 10 Tf 0 0 0 rg ( ) Tj (cache) Tj (:) Tj T* ( ) Tj /F3 10 Tf 0 .501961 0 rg (return) Tj /F5 10 Tf 0 0 0 rg ( ) Tj (cache) Tj ([) Tj (key) Tj (]) Tj T* ( ) Tj /F3 10 Tf 0 .501961 0 rg (else) Tj /F5 10 Tf 0 0 0 rg (:) Tj T* ( ) Tj (cache) Tj ([) Tj (key) Tj (]) Tj ( ) Tj .4 .4 .4 rg (=) Tj 0 0 0 rg ( ) Tj (result) Tj ( ) Tj .4 .4 .4 rg (=) Tj 0 0 0 rg ( ) Tj (func) Tj (\() Tj .4 .4 .4 rg (*) Tj 0 0 0 rg (args) Tj (,) Tj ( ) Tj .4 .4 .4 rg (**) Tj 0 0 0 rg (kw) Tj (\)) Tj T* ( ) Tj /F3 10 Tf 0 .501961 0 rg (return) Tj /F5 10 Tf 0 0 0 rg ( ) Tj (result) Tj T* ET +Q +Q +Q +Q +Q +q +1 0 0 1 62.69291 102.0236 cm +q +0 0 0 rg +BT 1 0 0 1 0 4.82 Tm /F1 10 Tf 12 TL (At this point you can define your decorator as follows:) Tj T* ET +Q +Q + +endstream + +endobj +% 'R84': class PDFStream +84 0 obj +% page stream +<< /Length 7170 >> +stream +1 0 0 1 0 0 cm BT /F1 12 Tf 14.4 TL ET +q +1 0 0 1 62.69291 715.8236 cm +q +q +1 0 0 1 0 0 cm +q +1 0 0 1 6.6 6.6 cm +q +.662745 .662745 .662745 RG +.5 w +.960784 .960784 .862745 rg +n -6 -6 468.6898 48 re B* +Q +q +BT 1 0 0 1 0 29.71 Tm 12 TL /F3 10 Tf 0 .501961 0 rg (def) Tj /F5 10 Tf 0 0 0 rg ( ) Tj 0 0 1 rg (memoize) Tj 0 0 0 rg (\() Tj (f) Tj (\):) Tj T* ( ) Tj (f) Tj .4 .4 .4 rg (.) Tj 0 0 0 rg (cache) Tj ( ) Tj .4 .4 .4 rg (=) Tj 0 0 0 rg ( ) Tj ({}) Tj T* ( ) Tj /F3 10 Tf 0 .501961 0 rg (return) Tj /F5 10 Tf 0 0 0 rg ( ) Tj (decorator) Tj (\() Tj (_memoize) Tj (,) Tj ( ) Tj (f) Tj (\)) Tj T* ET +Q +Q +Q +Q +Q +q +1 0 0 1 62.69291 671.8236 cm +q +BT 1 0 0 1 0 28.82 Tm .12561 Tw 12 TL /F1 10 Tf 0 0 0 rg (The difference with respect to the ) Tj /F5 10 Tf (memoize_uw ) Tj /F1 10 Tf (approach, which is based on nested functions, is that the) Tj T* 0 Tw 2.59528 Tw (decorator module forces you to lift the inner function at the outer level \() Tj /F6 10 Tf (flat is better than nested) Tj /F1 10 Tf (\).) Tj T* 0 Tw (Moreover, you are forced to pass explicitly the function you want to decorate to the caller function.) Tj T* ET +Q +Q +q +1 0 0 1 62.69291 653.8236 cm +q +0 0 0 rg +BT 1 0 0 1 0 4.82 Tm /F1 10 Tf 12 TL (Here is a test of usage:) Tj T* ET +Q +Q +q +1 0 0 1 62.69291 512.6236 cm +q +q +1 0 0 1 0 0 cm +q +1 0 0 1 6.6 6.6 cm +q +.662745 .662745 .662745 RG +.5 w +.960784 .960784 .862745 rg +n -6 -6 468.6898 132 re B* +Q +q +BT 1 0 0 1 0 113.71 Tm 12 TL /F5 10 Tf .4 .4 .4 rg (>) Tj (>) Tj (>) Tj 0 0 0 rg ( ) Tj .666667 .133333 1 rg (@memoize) Tj 0 0 0 rg T* .4 .4 .4 rg (...) Tj 0 0 0 rg ( ) Tj /F3 10 Tf 0 .501961 0 rg (def) Tj /F5 10 Tf 0 0 0 rg ( ) Tj 0 0 1 rg (heavy_computation) Tj 0 0 0 rg (\(\):) Tj T* .4 .4 .4 rg (...) Tj 0 0 0 rg ( ) Tj (time) Tj .4 .4 .4 rg (.) Tj 0 0 0 rg (sleep) Tj (\() Tj .4 .4 .4 rg (2) Tj 0 0 0 rg (\)) Tj T* .4 .4 .4 rg (...) Tj 0 0 0 rg ( ) Tj /F3 10 Tf 0 .501961 0 rg (return) Tj /F5 10 Tf 0 0 0 rg ( ) Tj .729412 .129412 .129412 rg ("done") Tj 0 0 0 rg T* T* .4 .4 .4 rg (>) Tj (>) Tj (>) Tj 0 0 0 rg ( ) Tj /F3 10 Tf 0 .501961 0 rg (print) Tj /F5 10 Tf 0 0 0 rg (\() Tj (heavy_computation) Tj (\(\)\)) Tj ( ) Tj /F7 10 Tf .25098 .501961 .501961 rg (# the first time it will take 2 seconds) Tj /F5 10 Tf 0 0 0 rg T* (done) Tj T* T* .4 .4 .4 rg (>) Tj (>) Tj (>) Tj 0 0 0 rg ( ) Tj /F3 10 Tf 0 .501961 0 rg (print) Tj /F5 10 Tf 0 0 0 rg (\() Tj (heavy_computation) Tj (\(\)\)) Tj ( ) Tj /F7 10 Tf .25098 .501961 .501961 rg (# the second time it will be instantaneous) Tj /F5 10 Tf 0 0 0 rg T* (done) Tj T* ET +Q +Q +Q +Q +Q +q +1 0 0 1 62.69291 492.6236 cm +q +BT 1 0 0 1 0 4.82 Tm 12 TL /F1 10 Tf 0 0 0 rg (The signature of ) Tj /F5 10 Tf (heavy_computation ) Tj /F1 10 Tf (is the one you would expect:) Tj T* ET +Q +Q +q +1 0 0 1 62.69291 447.4236 cm +q +q +1 0 0 1 0 0 cm +q +1 0 0 1 6.6 6.6 cm +q +.662745 .662745 .662745 RG +.5 w +.960784 .960784 .862745 rg +n -6 -6 468.6898 36 re B* +Q +q +BT 1 0 0 1 0 17.71 Tm 12 TL /F5 10 Tf .4 .4 .4 rg (>) Tj (>) Tj (>) Tj 0 0 0 rg ( ) Tj /F3 10 Tf 0 .501961 0 rg (print) Tj /F5 10 Tf 0 0 0 rg (\() Tj (getargspec) Tj (\() Tj (heavy_computation) Tj (\)\)) Tj T* (ArgSpec) Tj (\() Tj (args) Tj .4 .4 .4 rg (=) Tj 0 0 0 rg ([],) Tj ( ) Tj (varargs) Tj .4 .4 .4 rg (=) Tj 0 .501961 0 rg (None) Tj 0 0 0 rg (,) Tj ( ) Tj (keywords) Tj .4 .4 .4 rg (=) Tj 0 .501961 0 rg (None) Tj 0 0 0 rg (,) Tj ( ) Tj (defaults) Tj .4 .4 .4 rg (=) Tj 0 .501961 0 rg (None) Tj 0 0 0 rg (\)) Tj T* ET +Q +Q +Q +Q +Q +q +1 0 0 1 62.69291 414.4236 cm +q +BT 1 0 0 1 0 8.435 Tm 21 TL /F2 17.5 Tf 0 0 0 rg (A ) Tj /F3 17.5 Tf (trace ) Tj /F2 17.5 Tf (decorator) Tj T* ET +Q +Q +q +1 0 0 1 62.69291 384.4236 cm +q +BT 1 0 0 1 0 16.82 Tm .479398 Tw 12 TL /F1 10 Tf 0 0 0 rg (As an additional example, here is how you can define a trivial ) Tj /F5 10 Tf (trace ) Tj /F1 10 Tf (decorator, which prints a message) Tj T* 0 Tw (everytime the traced function is called:) Tj T* ET +Q +Q +q +1 0 0 1 62.69291 327.2236 cm +q +q +1 0 0 1 0 0 cm +q +1 0 0 1 6.6 6.6 cm +q +.662745 .662745 .662745 RG +.5 w +.960784 .960784 .862745 rg +n -6 -6 468.6898 48 re B* +Q +q +BT 1 0 0 1 0 29.71 Tm 12 TL /F3 10 Tf 0 .501961 0 rg (def) Tj /F5 10 Tf 0 0 0 rg ( ) Tj 0 0 1 rg (_trace) Tj 0 0 0 rg (\() Tj (f) Tj (,) Tj ( ) Tj .4 .4 .4 rg (*) Tj 0 0 0 rg (args) Tj (,) Tj ( ) Tj .4 .4 .4 rg (**) Tj 0 0 0 rg (kw) Tj (\):) Tj T* ( ) Tj /F3 10 Tf 0 .501961 0 rg (print) Tj /F5 10 Tf 0 0 0 rg (\() Tj .729412 .129412 .129412 rg ("calling ) Tj /F3 10 Tf .733333 .4 .533333 rg (%s) Tj /F5 10 Tf .729412 .129412 .129412 rg ( with args ) Tj /F3 10 Tf .733333 .4 .533333 rg (%s) Tj /F5 10 Tf .729412 .129412 .129412 rg (, ) Tj /F3 10 Tf .733333 .4 .533333 rg (%s) Tj /F5 10 Tf .729412 .129412 .129412 rg (") Tj 0 0 0 rg ( ) Tj .4 .4 .4 rg (%) Tj 0 0 0 rg ( ) Tj (\() Tj (f) Tj .4 .4 .4 rg (.) Tj 0 0 0 rg (__name__) Tj (,) Tj ( ) Tj (args) Tj (,) Tj ( ) Tj (kw) Tj (\)\)) Tj T* ( ) Tj /F3 10 Tf 0 .501961 0 rg (return) Tj /F5 10 Tf 0 0 0 rg ( ) Tj (f) Tj (\() Tj .4 .4 .4 rg (*) Tj 0 0 0 rg (args) Tj (,) Tj ( ) Tj .4 .4 .4 rg (**) Tj 0 0 0 rg (kw) Tj (\)) Tj T* ET +Q +Q +Q +Q +Q +q +1 0 0 1 62.69291 282.0236 cm +q +q +1 0 0 1 0 0 cm +q +1 0 0 1 6.6 6.6 cm +q +.662745 .662745 .662745 RG +.5 w +.960784 .960784 .862745 rg +n -6 -6 468.6898 36 re B* +Q +q +BT 1 0 0 1 0 17.71 Tm 12 TL /F3 10 Tf 0 .501961 0 rg (def) Tj /F5 10 Tf 0 0 0 rg ( ) Tj 0 0 1 rg (trace) Tj 0 0 0 rg (\() Tj (f) Tj (\):) Tj T* ( ) Tj /F3 10 Tf 0 .501961 0 rg (return) Tj /F5 10 Tf 0 0 0 rg ( ) Tj (decorator) Tj (\() Tj (_trace) Tj (,) Tj ( ) Tj (f) Tj (\)) Tj T* ET +Q +Q +Q +Q +Q +q +1 0 0 1 62.69291 262.0236 cm +q +0 0 0 rg +BT 1 0 0 1 0 4.82 Tm /F1 10 Tf 12 TL (Here is an example of usage:) Tj T* ET +Q +Q +q +1 0 0 1 62.69291 204.8236 cm +q +q +1 0 0 1 0 0 cm +q +1 0 0 1 6.6 6.6 cm +q +.662745 .662745 .662745 RG +.5 w +.960784 .960784 .862745 rg +n -6 -6 468.6898 48 re B* +Q +q +BT 1 0 0 1 0 29.71 Tm 12 TL /F5 10 Tf .4 .4 .4 rg (>) Tj (>) Tj (>) Tj 0 0 0 rg ( ) Tj .666667 .133333 1 rg (@trace) Tj 0 0 0 rg T* .4 .4 .4 rg (...) Tj 0 0 0 rg ( ) Tj /F3 10 Tf 0 .501961 0 rg (def) Tj /F5 10 Tf 0 0 0 rg ( ) Tj 0 0 1 rg (f1) Tj 0 0 0 rg (\() Tj (x) Tj (\):) Tj T* .4 .4 .4 rg (...) Tj 0 0 0 rg ( ) Tj /F3 10 Tf 0 .501961 0 rg (pass) Tj T* ET +Q +Q +Q +Q +Q +q +1 0 0 1 62.69291 184.8236 cm +q +BT 1 0 0 1 0 4.82 Tm 12 TL /F1 10 Tf 0 0 0 rg (It is immediate to verify that ) Tj /F5 10 Tf (f1 ) Tj /F1 10 Tf (works) Tj T* ET +Q +Q +q +1 0 0 1 62.69291 139.6236 cm +q +q +1 0 0 1 0 0 cm +q +1 0 0 1 6.6 6.6 cm +q +.662745 .662745 .662745 RG +.5 w +.960784 .960784 .862745 rg +n -6 -6 468.6898 36 re B* +Q +q +BT 1 0 0 1 0 17.71 Tm 12 TL /F5 10 Tf .4 .4 .4 rg (>) Tj (>) Tj (>) Tj 0 0 0 rg ( ) Tj (f1) Tj (\() Tj .4 .4 .4 rg (0) Tj 0 0 0 rg (\)) Tj T* (calling) Tj ( ) Tj (f1) Tj ( ) Tj /F3 10 Tf 0 .501961 0 rg (with) Tj /F5 10 Tf 0 0 0 rg ( ) Tj (args) Tj ( ) Tj (\() Tj .4 .4 .4 rg (0) Tj 0 0 0 rg (,\),) Tj ( ) Tj ({}) Tj T* ET +Q +Q +Q +Q +Q +q +1 0 0 1 62.69291 119.6236 cm +q +0 0 0 rg +BT 1 0 0 1 0 4.82 Tm /F1 10 Tf 12 TL (and it that it has the correct signature:) Tj T* ET +Q +Q + +endstream + +endobj +% 'R85': class PDFStream +85 0 obj +% page stream +<< /Length 8309 >> +stream +1 0 0 1 0 0 cm BT /F1 12 Tf 14.4 TL ET +q +1 0 0 1 62.69291 727.8236 cm +q +q +1 0 0 1 0 0 cm +q +1 0 0 1 6.6 6.6 cm +q +.662745 .662745 .662745 RG +.5 w +.960784 .960784 .862745 rg +n -6 -6 468.6898 36 re B* +Q +q +BT 1 0 0 1 0 17.71 Tm 12 TL /F5 10 Tf .4 .4 .4 rg (>) Tj (>) Tj (>) Tj 0 0 0 rg ( ) Tj /F3 10 Tf 0 .501961 0 rg (print) Tj /F5 10 Tf 0 0 0 rg (\() Tj (getargspec) Tj (\() Tj (f1) Tj (\)\)) Tj T* (ArgSpec) Tj (\() Tj (args) Tj .4 .4 .4 rg (=) Tj 0 0 0 rg ([) Tj .729412 .129412 .129412 rg ('x') Tj 0 0 0 rg (],) Tj ( ) Tj (varargs) Tj .4 .4 .4 rg (=) Tj 0 .501961 0 rg (None) Tj 0 0 0 rg (,) Tj ( ) Tj (keywords) Tj .4 .4 .4 rg (=) Tj 0 .501961 0 rg (None) Tj 0 0 0 rg (,) Tj ( ) Tj (defaults) Tj .4 .4 .4 rg (=) Tj 0 .501961 0 rg (None) Tj 0 0 0 rg (\)) Tj T* ET +Q +Q +Q +Q +Q +q +1 0 0 1 62.69291 707.8236 cm +q +0 0 0 rg +BT 1 0 0 1 0 4.82 Tm /F1 10 Tf 12 TL (The same decorator works with functions of any signature:) Tj T* ET +Q +Q +q +1 0 0 1 62.69291 579.978 cm +q +q +.988825 0 0 .988825 0 0 cm +q +1 0 0 1 6.6 6.674587 cm +q +.662745 .662745 .662745 RG +.5 w +.960784 .960784 .862745 rg +n -6 -6 474 120 re B* +Q +q +BT 1 0 0 1 0 101.71 Tm 12 TL /F5 10 Tf .4 .4 .4 rg (>) Tj (>) Tj (>) Tj 0 0 0 rg ( ) Tj .666667 .133333 1 rg (@trace) Tj 0 0 0 rg T* .4 .4 .4 rg (...) Tj 0 0 0 rg ( ) Tj /F3 10 Tf 0 .501961 0 rg (def) Tj /F5 10 Tf 0 0 0 rg ( ) Tj 0 0 1 rg (f) Tj 0 0 0 rg (\() Tj (x) Tj (,) Tj ( ) Tj (y) Tj .4 .4 .4 rg (=) Tj (1) Tj 0 0 0 rg (,) Tj ( ) Tj (z) Tj .4 .4 .4 rg (=) Tj (2) Tj 0 0 0 rg (,) Tj ( ) Tj .4 .4 .4 rg (*) Tj 0 0 0 rg (args) Tj (,) Tj ( ) Tj .4 .4 .4 rg (**) Tj 0 0 0 rg (kw) Tj (\):) Tj T* .4 .4 .4 rg (...) Tj 0 0 0 rg ( ) Tj /F3 10 Tf 0 .501961 0 rg (pass) Tj /F5 10 Tf 0 0 0 rg T* T* .4 .4 .4 rg (>) Tj (>) Tj (>) Tj 0 0 0 rg ( ) Tj (f) Tj (\() Tj .4 .4 .4 rg (0) Tj 0 0 0 rg (,) Tj ( ) Tj .4 .4 .4 rg (3) Tj 0 0 0 rg (\)) Tj T* (calling) Tj ( ) Tj (f) Tj ( ) Tj /F3 10 Tf 0 .501961 0 rg (with) Tj /F5 10 Tf 0 0 0 rg ( ) Tj (args) Tj ( ) Tj (\() Tj .4 .4 .4 rg (0) Tj 0 0 0 rg (,) Tj ( ) Tj .4 .4 .4 rg (3) Tj 0 0 0 rg (,) Tj ( ) Tj .4 .4 .4 rg (2) Tj 0 0 0 rg (\),) Tj ( ) Tj ({}) Tj T* T* .4 .4 .4 rg (>) Tj (>) Tj (>) Tj 0 0 0 rg ( ) Tj /F3 10 Tf 0 .501961 0 rg (print) Tj /F5 10 Tf 0 0 0 rg (\() Tj (getargspec) Tj (\() Tj (f) Tj (\)\)) Tj T* (ArgSpec) Tj (\() Tj (args) Tj .4 .4 .4 rg (=) Tj 0 0 0 rg ([) Tj .729412 .129412 .129412 rg ('x') Tj 0 0 0 rg (,) Tj ( ) Tj .729412 .129412 .129412 rg ('y') Tj 0 0 0 rg (,) Tj ( ) Tj .729412 .129412 .129412 rg ('z') Tj 0 0 0 rg (],) Tj ( ) Tj (varargs) Tj .4 .4 .4 rg (=) Tj .729412 .129412 .129412 rg ('args') Tj 0 0 0 rg (,) Tj ( ) Tj (keywords) Tj .4 .4 .4 rg (=) Tj .729412 .129412 .129412 rg ('kw') Tj 0 0 0 rg (,) Tj ( ) Tj (defaults) Tj .4 .4 .4 rg (=) Tj 0 0 0 rg (\() Tj .4 .4 .4 rg (1) Tj 0 0 0 rg (,) Tj ( ) Tj .4 .4 .4 rg (2) Tj 0 0 0 rg (\)\)) Tj T* ET +Q +Q +Q +Q +Q +q +1 0 0 1 62.69291 546.978 cm +q +BT 1 0 0 1 0 8.435 Tm 21 TL /F3 17.5 Tf 0 0 0 rg (decorator ) Tj /F2 17.5 Tf (is a decorator) Tj T* ET +Q +Q +q +1 0 0 1 62.69291 444.978 cm +q +BT 1 0 0 1 0 88.82 Tm .643876 Tw 12 TL /F1 10 Tf 0 0 0 rg (It may be annoying to write a caller function \(like the ) Tj /F5 10 Tf (_trace ) Tj /F1 10 Tf (function above\) and then a trivial wrapper) Tj T* 0 Tw 1.803615 Tw (\() Tj /F5 10 Tf (def trace\(f\): return decorator\(_trace, f\)) Tj /F1 10 Tf (\) every time. For this reason, the ) Tj /F5 10 Tf (decorator) Tj T* 0 Tw .334269 Tw /F1 10 Tf (module provides an easy shortcut to convert the caller function into a signature-preserving decorator: you) Tj T* 0 Tw 3.443735 Tw (can just call ) Tj /F5 10 Tf (decorator ) Tj /F1 10 Tf (with a single argument. In our example you can just write ) Tj /F5 10 Tf (trace =) Tj T* 0 Tw 1.056342 Tw (decorator\(_trace\)) Tj /F1 10 Tf (. The ) Tj /F5 10 Tf (decorator ) Tj /F1 10 Tf (function can also be used as a signature-changing decorator,) Tj T* 0 Tw 3.177752 Tw (just as ) Tj /F5 10 Tf (classmethod ) Tj /F1 10 Tf (and ) Tj /F5 10 Tf (staticmethod) Tj /F1 10 Tf (. However, ) Tj /F5 10 Tf (classmethod ) Tj /F1 10 Tf (and ) Tj /F5 10 Tf (staticmethod ) Tj /F1 10 Tf (return) Tj T* 0 Tw 1.693615 Tw (generic objects which are not callable, while ) Tj /F5 10 Tf (decorator ) Tj /F1 10 Tf (returns signature-preserving decorators, i.e.) Tj T* 0 Tw (functions of a single argument. For instance, you can write directly) Tj T* ET +Q +Q +q +1 0 0 1 62.69291 375.778 cm +q +q +1 0 0 1 0 0 cm +q +1 0 0 1 6.6 6.6 cm +q +.662745 .662745 .662745 RG +.5 w +.960784 .960784 .862745 rg +n -6 -6 468.6898 60 re B* +Q +q +BT 1 0 0 1 0 41.71 Tm 12 TL /F5 10 Tf .4 .4 .4 rg (>) Tj (>) Tj (>) Tj 0 0 0 rg ( ) Tj .666667 .133333 1 rg (@decorator) Tj 0 0 0 rg T* .4 .4 .4 rg (...) Tj 0 0 0 rg ( ) Tj /F3 10 Tf 0 .501961 0 rg (def) Tj /F5 10 Tf 0 0 0 rg ( ) Tj 0 0 1 rg (trace) Tj 0 0 0 rg (\() Tj (f) Tj (,) Tj ( ) Tj .4 .4 .4 rg (*) Tj 0 0 0 rg (args) Tj (,) Tj ( ) Tj .4 .4 .4 rg (**) Tj 0 0 0 rg (kw) Tj (\):) Tj T* .4 .4 .4 rg (...) Tj 0 0 0 rg ( ) Tj /F3 10 Tf 0 .501961 0 rg (print) Tj /F5 10 Tf 0 0 0 rg (\() Tj .729412 .129412 .129412 rg ("calling ) Tj /F3 10 Tf .733333 .4 .533333 rg (%s) Tj /F5 10 Tf .729412 .129412 .129412 rg ( with args ) Tj /F3 10 Tf .733333 .4 .533333 rg (%s) Tj /F5 10 Tf .729412 .129412 .129412 rg (, ) Tj /F3 10 Tf .733333 .4 .533333 rg (%s) Tj /F5 10 Tf .729412 .129412 .129412 rg (") Tj 0 0 0 rg ( ) Tj .4 .4 .4 rg (%) Tj 0 0 0 rg ( ) Tj (\() Tj (f) Tj .4 .4 .4 rg (.) Tj 0 0 0 rg (__name__) Tj (,) Tj ( ) Tj (args) Tj (,) Tj ( ) Tj (kw) Tj (\)\)) Tj T* .4 .4 .4 rg (...) Tj 0 0 0 rg ( ) Tj /F3 10 Tf 0 .501961 0 rg (return) Tj /F5 10 Tf 0 0 0 rg ( ) Tj (f) Tj (\() Tj .4 .4 .4 rg (*) Tj 0 0 0 rg (args) Tj (,) Tj ( ) Tj .4 .4 .4 rg (**) Tj 0 0 0 rg (kw) Tj (\)) Tj T* ET +Q +Q +Q +Q +Q +q +1 0 0 1 62.69291 343.778 cm +q +BT 1 0 0 1 0 16.82 Tm 1.806654 Tw 12 TL /F1 10 Tf 0 0 0 rg (and now ) Tj /F5 10 Tf (trace ) Tj /F1 10 Tf (will be a decorator. Actually ) Tj /F5 10 Tf (trace ) Tj /F1 10 Tf (is a ) Tj /F5 10 Tf (partial ) Tj /F1 10 Tf (object which can be used as a) Tj T* 0 Tw (decorator:) Tj T* ET +Q +Q +q +1 0 0 1 62.69291 298.578 cm +q +q +1 0 0 1 0 0 cm +q +1 0 0 1 6.6 6.6 cm +q +.662745 .662745 .662745 RG +.5 w +.960784 .960784 .862745 rg +n -6 -6 468.6898 36 re B* +Q +q +BT 1 0 0 1 0 17.71 Tm 12 TL /F5 10 Tf .4 .4 .4 rg (>) Tj (>) Tj (>) Tj 0 0 0 rg ( ) Tj (trace) Tj T* .4 .4 .4 rg (<) Tj 0 0 0 rg (function) Tj ( ) Tj (trace) Tj ( ) Tj (at) Tj ( ) Tj .4 .4 .4 rg (0) Tj 0 0 0 rg (x) Tj .4 .4 .4 rg (...) Tj (>) Tj T* ET +Q +Q +Q +Q +Q +q +1 0 0 1 62.69291 278.578 cm +q +0 0 0 rg +BT 1 0 0 1 0 4.82 Tm /F1 10 Tf 12 TL (Here is an example of usage:) Tj T* ET +Q +Q +q +1 0 0 1 62.69291 197.378 cm +q +q +1 0 0 1 0 0 cm +q +1 0 0 1 6.6 6.6 cm +q +.662745 .662745 .662745 RG +.5 w +.960784 .960784 .862745 rg +n -6 -6 468.6898 72 re B* +Q +q +BT 1 0 0 1 0 53.71 Tm 12 TL /F5 10 Tf .4 .4 .4 rg (>) Tj (>) Tj (>) Tj 0 0 0 rg ( ) Tj .666667 .133333 1 rg (@trace) Tj 0 0 0 rg T* .4 .4 .4 rg (...) Tj 0 0 0 rg ( ) Tj /F3 10 Tf 0 .501961 0 rg (def) Tj /F5 10 Tf 0 0 0 rg ( ) Tj 0 0 1 rg (func) Tj 0 0 0 rg (\(\):) Tj ( ) Tj /F3 10 Tf 0 .501961 0 rg (pass) Tj /F5 10 Tf 0 0 0 rg T* T* .4 .4 .4 rg (>) Tj (>) Tj (>) Tj 0 0 0 rg ( ) Tj (func) Tj (\(\)) Tj T* (calling) Tj ( ) Tj (func) Tj ( ) Tj /F3 10 Tf 0 .501961 0 rg (with) Tj /F5 10 Tf 0 0 0 rg ( ) Tj (args) Tj ( ) Tj (\(\),) Tj ( ) Tj ({}) Tj T* ET +Q +Q +Q +Q +Q +q +1 0 0 1 62.69291 165.378 cm +q +BT 1 0 0 1 0 16.82 Tm 2.44686 Tw 12 TL /F1 10 Tf 0 0 0 rg (If you are using an old Python version \(Python 2.4\) the ) Tj /F5 10 Tf (decorator ) Tj /F1 10 Tf (module provides a poor man) Tj T* 0 Tw (replacement for ) Tj /F5 10 Tf (functools.partial) Tj /F1 10 Tf (.) Tj T* ET +Q +Q +q +1 0 0 1 62.69291 132.378 cm +q +BT 1 0 0 1 0 8.435 Tm 21 TL /F3 17.5 Tf 0 0 0 rg (blocking) Tj T* ET +Q +Q +q +1 0 0 1 62.69291 90.378 cm +q +BT 1 0 0 1 0 28.82 Tm 1.224692 Tw 12 TL /F1 10 Tf 0 0 0 rg (Sometimes one has to deal with blocking resources, such as ) Tj /F5 10 Tf (stdin) Tj /F1 10 Tf (, and sometimes it is best to have) Tj T* 0 Tw .266235 Tw (back a "busy" message than to block everything. This behavior can be implemented with a suitable family) Tj T* 0 Tw (of decorators, where the parameter is the busy message:) Tj T* ET +Q +Q + +endstream + +endobj +% 'R86': class PDFStream +86 0 obj +% page stream +<< /Length 7602 >> +stream +1 0 0 1 0 0 cm BT /F1 12 Tf 14.4 TL ET +q +1 0 0 1 62.69291 595.8236 cm +q +q +1 0 0 1 0 0 cm +q +1 0 0 1 6.6 6.6 cm +q +.662745 .662745 .662745 RG +.5 w +.960784 .960784 .862745 rg +n -6 -6 468.6898 168 re B* +Q +q +BT 1 0 0 1 0 149.71 Tm 12 TL /F3 10 Tf 0 .501961 0 rg (def) Tj /F5 10 Tf 0 0 0 rg ( ) Tj 0 0 1 rg (blocking) Tj 0 0 0 rg (\() Tj (not_avail) Tj (\):) Tj T* ( ) Tj /F3 10 Tf 0 .501961 0 rg (def) Tj /F5 10 Tf 0 0 0 rg ( ) Tj 0 0 1 rg (blocking) Tj 0 0 0 rg (\() Tj (f) Tj (,) Tj ( ) Tj .4 .4 .4 rg (*) Tj 0 0 0 rg (args) Tj (,) Tj ( ) Tj .4 .4 .4 rg (**) Tj 0 0 0 rg (kw) Tj (\):) Tj T* ( ) Tj /F3 10 Tf 0 .501961 0 rg (if) Tj /F5 10 Tf 0 0 0 rg ( ) Tj /F3 10 Tf .666667 .133333 1 rg (not) Tj /F5 10 Tf 0 0 0 rg ( ) Tj 0 .501961 0 rg (hasattr) Tj 0 0 0 rg (\() Tj (f) Tj (,) Tj ( ) Tj .729412 .129412 .129412 rg ("thread") Tj 0 0 0 rg (\):) Tj ( ) Tj /F7 10 Tf .25098 .501961 .501961 rg (# no thread running) Tj /F5 10 Tf 0 0 0 rg T* ( ) Tj /F3 10 Tf 0 .501961 0 rg (def) Tj /F5 10 Tf 0 0 0 rg ( ) Tj 0 0 1 rg (set_result) Tj 0 0 0 rg (\(\):) Tj ( ) Tj (f) Tj .4 .4 .4 rg (.) Tj 0 0 0 rg (result) Tj ( ) Tj .4 .4 .4 rg (=) Tj 0 0 0 rg ( ) Tj (f) Tj (\() Tj .4 .4 .4 rg (*) Tj 0 0 0 rg (args) Tj (,) Tj ( ) Tj .4 .4 .4 rg (**) Tj 0 0 0 rg (kw) Tj (\)) Tj T* ( ) Tj (f) Tj .4 .4 .4 rg (.) Tj 0 0 0 rg (thread) Tj ( ) Tj .4 .4 .4 rg (=) Tj 0 0 0 rg ( ) Tj (threading) Tj .4 .4 .4 rg (.) Tj 0 0 0 rg (Thread) Tj (\() Tj 0 .501961 0 rg (None) Tj 0 0 0 rg (,) Tj ( ) Tj (set_result) Tj (\)) Tj T* ( ) Tj (f) Tj .4 .4 .4 rg (.) Tj 0 0 0 rg (thread) Tj .4 .4 .4 rg (.) Tj 0 0 0 rg (start) Tj (\(\)) Tj T* ( ) Tj /F3 10 Tf 0 .501961 0 rg (return) Tj /F5 10 Tf 0 0 0 rg ( ) Tj (not_avail) Tj T* ( ) Tj /F3 10 Tf 0 .501961 0 rg (elif) Tj /F5 10 Tf 0 0 0 rg ( ) Tj (f) Tj .4 .4 .4 rg (.) Tj 0 0 0 rg (thread) Tj .4 .4 .4 rg (.) Tj 0 0 0 rg (isAlive) Tj (\(\):) Tj T* ( ) Tj /F3 10 Tf 0 .501961 0 rg (return) Tj /F5 10 Tf 0 0 0 rg ( ) Tj (not_avail) Tj T* ( ) Tj /F3 10 Tf 0 .501961 0 rg (else) Tj /F5 10 Tf 0 0 0 rg (:) Tj ( ) Tj /F7 10 Tf .25098 .501961 .501961 rg (# the thread is ended, return the stored result) Tj /F5 10 Tf 0 0 0 rg T* ( ) Tj /F3 10 Tf 0 .501961 0 rg (del) Tj /F5 10 Tf 0 0 0 rg ( ) Tj (f) Tj .4 .4 .4 rg (.) Tj 0 0 0 rg (thread) Tj T* ( ) Tj /F3 10 Tf 0 .501961 0 rg (return) Tj /F5 10 Tf 0 0 0 rg ( ) Tj (f) Tj .4 .4 .4 rg (.) Tj 0 0 0 rg (result) Tj T* ( ) Tj /F3 10 Tf 0 .501961 0 rg (return) Tj /F5 10 Tf 0 0 0 rg ( ) Tj (decorator) Tj (\() Tj (blocking) Tj (\)) Tj T* ET +Q +Q +Q +Q +Q +q +1 0 0 1 62.69291 563.8236 cm +q +BT 1 0 0 1 0 16.82 Tm 1.010651 Tw 12 TL /F1 10 Tf 0 0 0 rg (Functions decorated with ) Tj /F5 10 Tf (blocking ) Tj /F1 10 Tf (will return a busy message if the resource is unavailable, and the) Tj T* 0 Tw (intended result if the resource is available. For instance:) Tj T* ET +Q +Q +q +1 0 0 1 62.69291 314.6236 cm +q +q +1 0 0 1 0 0 cm +q +1 0 0 1 6.6 6.6 cm +q +.662745 .662745 .662745 RG +.5 w +.960784 .960784 .862745 rg +n -6 -6 468.6898 240 re B* +Q +q +BT 1 0 0 1 0 221.71 Tm 12 TL /F5 10 Tf .4 .4 .4 rg (>) Tj (>) Tj (>) Tj 0 0 0 rg ( ) Tj .666667 .133333 1 rg (@blocking) Tj 0 0 0 rg (\() Tj .729412 .129412 .129412 rg ("Please wait ...") Tj 0 0 0 rg (\)) Tj T* .4 .4 .4 rg (...) Tj 0 0 0 rg ( ) Tj /F3 10 Tf 0 .501961 0 rg (def) Tj /F5 10 Tf 0 0 0 rg ( ) Tj 0 0 1 rg (read_data) Tj 0 0 0 rg (\(\):) Tj T* .4 .4 .4 rg (...) Tj 0 0 0 rg ( ) Tj (time) Tj .4 .4 .4 rg (.) Tj 0 0 0 rg (sleep) Tj (\() Tj .4 .4 .4 rg (3) Tj 0 0 0 rg (\)) Tj ( ) Tj /F7 10 Tf .25098 .501961 .501961 rg (# simulate a blocking resource) Tj /F5 10 Tf 0 0 0 rg T* .4 .4 .4 rg (...) Tj 0 0 0 rg ( ) Tj /F3 10 Tf 0 .501961 0 rg (return) Tj /F5 10 Tf 0 0 0 rg ( ) Tj .729412 .129412 .129412 rg ("some data") Tj 0 0 0 rg T* T* .4 .4 .4 rg (>) Tj (>) Tj (>) Tj 0 0 0 rg ( ) Tj /F3 10 Tf 0 .501961 0 rg (print) Tj /F5 10 Tf 0 0 0 rg (\() Tj (read_data) Tj (\(\)\)) Tj ( ) Tj /F7 10 Tf .25098 .501961 .501961 rg (# data is not available yet) Tj /F5 10 Tf 0 0 0 rg T* (Please) Tj ( ) Tj (wait) Tj ( ) Tj .4 .4 .4 rg (...) Tj 0 0 0 rg T* T* .4 .4 .4 rg (>) Tj (>) Tj (>) Tj 0 0 0 rg ( ) Tj (time) Tj .4 .4 .4 rg (.) Tj 0 0 0 rg (sleep) Tj (\() Tj .4 .4 .4 rg (1) Tj 0 0 0 rg (\)) Tj T* .4 .4 .4 rg (>) Tj (>) Tj (>) Tj 0 0 0 rg ( ) Tj /F3 10 Tf 0 .501961 0 rg (print) Tj /F5 10 Tf 0 0 0 rg (\() Tj (read_data) Tj (\(\)\)) Tj ( ) Tj /F7 10 Tf .25098 .501961 .501961 rg (# data is not available yet) Tj /F5 10 Tf 0 0 0 rg T* (Please) Tj ( ) Tj (wait) Tj ( ) Tj .4 .4 .4 rg (...) Tj 0 0 0 rg T* T* .4 .4 .4 rg (>) Tj (>) Tj (>) Tj 0 0 0 rg ( ) Tj (time) Tj .4 .4 .4 rg (.) Tj 0 0 0 rg (sleep) Tj (\() Tj .4 .4 .4 rg (1) Tj 0 0 0 rg (\)) Tj T* .4 .4 .4 rg (>) Tj (>) Tj (>) Tj 0 0 0 rg ( ) Tj /F3 10 Tf 0 .501961 0 rg (print) Tj /F5 10 Tf 0 0 0 rg (\() Tj (read_data) Tj (\(\)\)) Tj ( ) Tj /F7 10 Tf .25098 .501961 .501961 rg (# data is not available yet) Tj /F5 10 Tf 0 0 0 rg T* (Please) Tj ( ) Tj (wait) Tj ( ) Tj .4 .4 .4 rg (...) Tj 0 0 0 rg T* T* .4 .4 .4 rg (>) Tj (>) Tj (>) Tj 0 0 0 rg ( ) Tj (time) Tj .4 .4 .4 rg (.) Tj 0 0 0 rg (sleep) Tj (\() Tj .4 .4 .4 rg (1.1) Tj 0 0 0 rg (\)) Tj ( ) Tj /F7 10 Tf .25098 .501961 .501961 rg (# after 3.1 seconds, data is available) Tj /F5 10 Tf 0 0 0 rg T* .4 .4 .4 rg (>) Tj (>) Tj (>) Tj 0 0 0 rg ( ) Tj /F3 10 Tf 0 .501961 0 rg (print) Tj /F5 10 Tf 0 0 0 rg (\() Tj (read_data) Tj (\(\)\)) Tj T* (some) Tj ( ) Tj (data) Tj T* ET +Q +Q +Q +Q +Q +q +1 0 0 1 62.69291 281.6236 cm +q +BT 1 0 0 1 0 8.435 Tm 21 TL /F3 17.5 Tf 0 0 0 rg (async) Tj T* ET +Q +Q +q +1 0 0 1 62.69291 215.6236 cm +q +BT 1 0 0 1 0 52.82 Tm 1.647485 Tw 12 TL /F1 10 Tf 0 0 0 rg (We have just seen an examples of a simple decorator factory, implemented as a function returning a) Tj T* 0 Tw .29784 Tw (decorator. For more complex situations, it is more convenient to implement decorator factories as classes) Tj T* 0 Tw .657674 Tw (returning callable objects that can be used as signature-preserving decorators. The suggested pattern to) Tj T* 0 Tw 2.109398 Tw (do that is to introduce a helper method ) Tj /F5 10 Tf (call\(self, func, *args, **kw\) ) Tj /F1 10 Tf (and to call it in the) Tj T* 0 Tw /F5 10 Tf (__call__\(self, func\) ) Tj /F1 10 Tf (method.) Tj T* ET +Q +Q +q +1 0 0 1 62.69291 161.6236 cm +q +BT 1 0 0 1 0 40.82 Tm .166654 Tw 12 TL /F1 10 Tf 0 0 0 rg (As an example, here I show a decorator which is able to convert a blocking function into an asynchronous) Tj T* 0 Tw .437633 Tw (function. The function, when called, is executed in a separate thread. Moreover, it is possible to set three) Tj T* 0 Tw .074597 Tw (callbacks ) Tj /F5 10 Tf (on_success) Tj /F1 10 Tf (, ) Tj /F5 10 Tf (on_failure ) Tj /F1 10 Tf (and ) Tj /F5 10 Tf (on_closing) Tj /F1 10 Tf (, to specify how to manage the function call. The) Tj T* 0 Tw (implementation is the following:) Tj T* ET +Q +Q +q +1 0 0 1 62.69291 104.4236 cm +q +q +1 0 0 1 0 0 cm +q +1 0 0 1 6.6 6.6 cm +q +.662745 .662745 .662745 RG +.5 w +.960784 .960784 .862745 rg +n -6 -6 468.6898 48 re B* +Q +q +BT 1 0 0 1 0 29.71 Tm 12 TL /F3 10 Tf 0 .501961 0 rg (def) Tj /F5 10 Tf 0 0 0 rg ( ) Tj 0 0 1 rg (on_success) Tj 0 0 0 rg (\() Tj (result) Tj (\):) Tj ( ) Tj /F7 10 Tf .25098 .501961 .501961 rg (# default implementation) Tj /F5 10 Tf 0 0 0 rg T* ( ) Tj .729412 .129412 .129412 rg ("Called on the result of the function") Tj 0 0 0 rg T* ( ) Tj /F3 10 Tf 0 .501961 0 rg (return) Tj /F5 10 Tf 0 0 0 rg ( ) Tj (result) Tj T* ET +Q +Q +Q +Q +Q + +endstream + +endobj +% 'R87': class PDFStream +87 0 obj +% page stream +<< /Length 7304 >> +stream +1 0 0 1 0 0 cm BT /F1 12 Tf 14.4 TL ET +q +1 0 0 1 62.69291 715.8236 cm +q +q +1 0 0 1 0 0 cm +q +1 0 0 1 6.6 6.6 cm +q +.662745 .662745 .662745 RG +.5 w +.960784 .960784 .862745 rg +n -6 -6 468.6898 48 re B* +Q +q +BT 1 0 0 1 0 29.71 Tm 12 TL /F3 10 Tf 0 .501961 0 rg (def) Tj /F5 10 Tf 0 0 0 rg ( ) Tj 0 0 1 rg (on_failure) Tj 0 0 0 rg (\() Tj (exc_info) Tj (\):) Tj ( ) Tj /F7 10 Tf .25098 .501961 .501961 rg (# default implementation) Tj /F5 10 Tf 0 0 0 rg T* ( ) Tj .729412 .129412 .129412 rg ("Called if the function fails") Tj 0 0 0 rg T* ( ) Tj /F3 10 Tf 0 .501961 0 rg (pass) Tj T* ET +Q +Q +Q +Q +Q +q +1 0 0 1 62.69291 658.6236 cm +q +q +1 0 0 1 0 0 cm +q +1 0 0 1 6.6 6.6 cm +q +.662745 .662745 .662745 RG +.5 w +.960784 .960784 .862745 rg +n -6 -6 468.6898 48 re B* +Q +q +BT 1 0 0 1 0 29.71 Tm 12 TL /F3 10 Tf 0 .501961 0 rg (def) Tj /F5 10 Tf 0 0 0 rg ( ) Tj 0 0 1 rg (on_closing) Tj 0 0 0 rg (\(\):) Tj ( ) Tj /F7 10 Tf .25098 .501961 .501961 rg (# default implementation) Tj /F5 10 Tf 0 0 0 rg T* ( ) Tj .729412 .129412 .129412 rg ("Called at the end, both in case of success and failure") Tj 0 0 0 rg T* ( ) Tj /F3 10 Tf 0 .501961 0 rg (pass) Tj T* ET +Q +Q +Q +Q +Q +q +1 0 0 1 62.69291 217.4236 cm +q +q +1 0 0 1 0 0 cm +q +1 0 0 1 6.6 6.6 cm +q +.662745 .662745 .662745 RG +.5 w +.960784 .960784 .862745 rg +n -6 -6 468.6898 432 re B* +Q +q +BT 1 0 0 1 0 413.71 Tm 12 TL /F3 10 Tf 0 .501961 0 rg (class) Tj /F5 10 Tf 0 0 0 rg ( ) Tj /F3 10 Tf 0 0 1 rg (Async) Tj /F5 10 Tf 0 0 0 rg (\() Tj 0 .501961 0 rg (object) Tj 0 0 0 rg (\):) Tj T* ( ) Tj /F7 10 Tf .729412 .129412 .129412 rg (""") Tj T* ( A decorator converting blocking functions into asynchronous) Tj T* ( functions, by using threads or processes. Examples:) Tj T* T* ( async_with_threads = Async\(threading.Thread\)) Tj T* ( async_with_processes = Async\(multiprocessing.Process\)) Tj T* ( """) Tj /F5 10 Tf 0 0 0 rg T* T* ( ) Tj /F3 10 Tf 0 .501961 0 rg (def) Tj /F5 10 Tf 0 0 0 rg ( ) Tj 0 0 1 rg (__init__) Tj 0 0 0 rg (\() Tj 0 .501961 0 rg (self) Tj 0 0 0 rg (,) Tj ( ) Tj (threadfactory) Tj (\):) Tj T* ( ) Tj 0 .501961 0 rg (self) Tj .4 .4 .4 rg (.) Tj 0 0 0 rg (threadfactory) Tj ( ) Tj .4 .4 .4 rg (=) Tj 0 0 0 rg ( ) Tj (threadfactory) Tj T* T* ( ) Tj /F3 10 Tf 0 .501961 0 rg (def) Tj /F5 10 Tf 0 0 0 rg ( ) Tj 0 0 1 rg (__call__) Tj 0 0 0 rg (\() Tj 0 .501961 0 rg (self) Tj 0 0 0 rg (,) Tj ( ) Tj (func) Tj (,) Tj ( ) Tj (on_success) Tj .4 .4 .4 rg (=) Tj 0 0 0 rg (on_success) Tj (,) Tj T* ( ) Tj (on_failure) Tj .4 .4 .4 rg (=) Tj 0 0 0 rg (on_failure) Tj (,) Tj ( ) Tj (on_closing) Tj .4 .4 .4 rg (=) Tj 0 0 0 rg (on_closing) Tj (\):) Tj T* ( ) Tj /F7 10 Tf .25098 .501961 .501961 rg (# every decorated function has its own independent thread counter) Tj /F5 10 Tf 0 0 0 rg T* ( ) Tj (func) Tj .4 .4 .4 rg (.) Tj 0 0 0 rg (counter) Tj ( ) Tj .4 .4 .4 rg (=) Tj 0 0 0 rg ( ) Tj (itertools) Tj .4 .4 .4 rg (.) Tj 0 0 0 rg (count) Tj (\() Tj .4 .4 .4 rg (1) Tj 0 0 0 rg (\)) Tj T* ( ) Tj (func) Tj .4 .4 .4 rg (.) Tj 0 0 0 rg (on_success) Tj ( ) Tj .4 .4 .4 rg (=) Tj 0 0 0 rg ( ) Tj (on_success) Tj T* ( ) Tj (func) Tj .4 .4 .4 rg (.) Tj 0 0 0 rg (on_failure) Tj ( ) Tj .4 .4 .4 rg (=) Tj 0 0 0 rg ( ) Tj (on_failure) Tj T* ( ) Tj (func) Tj .4 .4 .4 rg (.) Tj 0 0 0 rg (on_closing) Tj ( ) Tj .4 .4 .4 rg (=) Tj 0 0 0 rg ( ) Tj (on_closing) Tj T* ( ) Tj /F3 10 Tf 0 .501961 0 rg (return) Tj /F5 10 Tf 0 0 0 rg ( ) Tj (decorator) Tj (\() Tj 0 .501961 0 rg (self) Tj .4 .4 .4 rg (.) Tj 0 0 0 rg (call) Tj (,) Tj ( ) Tj (func) Tj (\)) Tj T* T* ( ) Tj /F3 10 Tf 0 .501961 0 rg (def) Tj /F5 10 Tf 0 0 0 rg ( ) Tj 0 0 1 rg (call) Tj 0 0 0 rg (\() Tj 0 .501961 0 rg (self) Tj 0 0 0 rg (,) Tj ( ) Tj (func) Tj (,) Tj ( ) Tj .4 .4 .4 rg (*) Tj 0 0 0 rg (args) Tj (,) Tj ( ) Tj .4 .4 .4 rg (**) Tj 0 0 0 rg (kw) Tj (\):) Tj T* ( ) Tj /F3 10 Tf 0 .501961 0 rg (def) Tj /F5 10 Tf 0 0 0 rg ( ) Tj 0 0 1 rg (func_wrapper) Tj 0 0 0 rg (\(\):) Tj T* ( ) Tj /F3 10 Tf 0 .501961 0 rg (try) Tj /F5 10 Tf 0 0 0 rg (:) Tj T* ( ) Tj (result) Tj ( ) Tj .4 .4 .4 rg (=) Tj 0 0 0 rg ( ) Tj (func) Tj (\() Tj .4 .4 .4 rg (*) Tj 0 0 0 rg (args) Tj (,) Tj ( ) Tj .4 .4 .4 rg (**) Tj 0 0 0 rg (kw) Tj (\)) Tj T* ( ) Tj /F3 10 Tf 0 .501961 0 rg (except) Tj /F5 10 Tf 0 0 0 rg (:) Tj T* ( ) Tj (func) Tj .4 .4 .4 rg (.) Tj 0 0 0 rg (on_failure) Tj (\() Tj (sys) Tj .4 .4 .4 rg (.) Tj 0 0 0 rg (exc_info) Tj (\(\)\)) Tj T* ( ) Tj /F3 10 Tf 0 .501961 0 rg (else) Tj /F5 10 Tf 0 0 0 rg (:) Tj T* ( ) Tj /F3 10 Tf 0 .501961 0 rg (return) Tj /F5 10 Tf 0 0 0 rg ( ) Tj (func) Tj .4 .4 .4 rg (.) Tj 0 0 0 rg (on_success) Tj (\() Tj (result) Tj (\)) Tj T* ( ) Tj /F3 10 Tf 0 .501961 0 rg (finally) Tj /F5 10 Tf 0 0 0 rg (:) Tj T* ( ) Tj (func) Tj .4 .4 .4 rg (.) Tj 0 0 0 rg (on_closing) Tj (\(\)) Tj T* ( ) Tj (name) Tj ( ) Tj .4 .4 .4 rg (=) Tj 0 0 0 rg ( ) Tj .729412 .129412 .129412 rg (') Tj /F3 10 Tf .733333 .4 .533333 rg (%s) Tj /F5 10 Tf .729412 .129412 .129412 rg (-) Tj /F3 10 Tf .733333 .4 .533333 rg (%s) Tj /F5 10 Tf .729412 .129412 .129412 rg (') Tj 0 0 0 rg ( ) Tj .4 .4 .4 rg (%) Tj 0 0 0 rg ( ) Tj (\() Tj (func) Tj .4 .4 .4 rg (.) Tj 0 0 0 rg (__name__) Tj (,) Tj ( ) Tj (next) Tj (\() Tj (func) Tj .4 .4 .4 rg (.) Tj 0 0 0 rg (counter) Tj (\)\)) Tj T* ( ) Tj (thread) Tj ( ) Tj .4 .4 .4 rg (=) Tj 0 0 0 rg ( ) Tj 0 .501961 0 rg (self) Tj .4 .4 .4 rg (.) Tj 0 0 0 rg (threadfactory) Tj (\() Tj 0 .501961 0 rg (None) Tj 0 0 0 rg (,) Tj ( ) Tj (func_wrapper) Tj (,) Tj ( ) Tj (name) Tj (\)) Tj T* ( ) Tj (thread) Tj .4 .4 .4 rg (.) Tj 0 0 0 rg (start) Tj (\(\)) Tj T* ( ) Tj /F3 10 Tf 0 .501961 0 rg (return) Tj /F5 10 Tf 0 0 0 rg ( ) Tj (thread) Tj T* ET +Q +Q +Q +Q +Q +q +1 0 0 1 62.69291 185.4236 cm +q +BT 1 0 0 1 0 16.82 Tm .865984 Tw 12 TL /F1 10 Tf 0 0 0 rg (The decorated function returns the current execution thread, which can be stored and checked later, for) Tj T* 0 Tw (instance to verify that the thread ) Tj /F5 10 Tf (.isAlive\(\)) Tj /F1 10 Tf (.) Tj T* ET +Q +Q +q +1 0 0 1 62.69291 143.4236 cm +q +0 0 0 rg +BT 1 0 0 1 0 28.82 Tm /F1 10 Tf 12 TL .691654 Tw (Here is an example of usage. Suppose one wants to write some data to an external resource which can) Tj T* 0 Tw .21683 Tw (be accessed by a single user at once \(for instance a printer\). Then the access to the writing function must) Tj T* 0 Tw (be locked. Here is a minimalistic example:) Tj T* ET +Q +Q +q +1 0 0 1 62.69291 86.22362 cm +q +q +1 0 0 1 0 0 cm +q +1 0 0 1 6.6 6.6 cm +q +.662745 .662745 .662745 RG +.5 w +.960784 .960784 .862745 rg +n -6 -6 468.6898 48 re B* +Q +q +BT 1 0 0 1 0 29.71 Tm 12 TL /F5 10 Tf .4 .4 .4 rg (>) Tj (>) Tj (>) Tj 0 0 0 rg ( ) Tj (async) Tj ( ) Tj .4 .4 .4 rg (=) Tj 0 0 0 rg ( ) Tj (Async) Tj (\() Tj (threading) Tj .4 .4 .4 rg (.) Tj 0 0 0 rg (Thread) Tj (\)) Tj T* T* .4 .4 .4 rg (>) Tj (>) Tj (>) Tj 0 0 0 rg ( ) Tj (datalist) Tj ( ) Tj .4 .4 .4 rg (=) Tj 0 0 0 rg ( ) Tj ([]) Tj ( ) Tj /F7 10 Tf .25098 .501961 .501961 rg (# for simplicity the written data are stored into a list.) Tj /F5 10 Tf 0 0 0 rg T* ET +Q +Q +Q +Q +Q + +endstream + +endobj +% 'R88': class PDFStream +88 0 obj +% page stream +<< /Length 7280 >> +stream +1 0 0 1 0 0 cm BT /F1 12 Tf 14.4 TL ET +q +1 0 0 1 62.69291 655.8236 cm +q +q +1 0 0 1 0 0 cm +q +1 0 0 1 6.6 6.6 cm +q +.662745 .662745 .662745 RG +.5 w +.960784 .960784 .862745 rg +n -6 -6 468.6898 108 re B* +Q +q +BT 1 0 0 1 0 89.71 Tm 12 TL /F5 10 Tf 0 0 0 rg T* .4 .4 .4 rg (>) Tj (>) Tj (>) Tj 0 0 0 rg ( ) Tj .666667 .133333 1 rg (@async) Tj 0 0 0 rg T* .4 .4 .4 rg (...) Tj 0 0 0 rg ( ) Tj /F3 10 Tf 0 .501961 0 rg (def) Tj /F5 10 Tf 0 0 0 rg ( ) Tj 0 0 1 rg (write) Tj 0 0 0 rg (\() Tj (data) Tj (\):) Tj T* .4 .4 .4 rg (...) Tj 0 0 0 rg ( ) Tj /F7 10 Tf .25098 .501961 .501961 rg (# append data to the datalist by locking) Tj /F5 10 Tf 0 0 0 rg T* .4 .4 .4 rg (...) Tj 0 0 0 rg ( ) Tj /F3 10 Tf 0 .501961 0 rg (with) Tj /F5 10 Tf 0 0 0 rg ( ) Tj (threading) Tj .4 .4 .4 rg (.) Tj 0 0 0 rg (Lock) Tj (\(\):) Tj T* .4 .4 .4 rg (...) Tj 0 0 0 rg ( ) Tj (time) Tj .4 .4 .4 rg (.) Tj 0 0 0 rg (sleep) Tj (\() Tj .4 .4 .4 rg (1) Tj 0 0 0 rg (\)) Tj ( ) Tj /F7 10 Tf .25098 .501961 .501961 rg (# emulate some long running operation) Tj /F5 10 Tf 0 0 0 rg T* .4 .4 .4 rg (...) Tj 0 0 0 rg ( ) Tj (datalist) Tj .4 .4 .4 rg (.) Tj 0 0 0 rg (append) Tj (\() Tj (data) Tj (\)) Tj T* .4 .4 .4 rg (...) Tj 0 0 0 rg ( ) Tj /F7 10 Tf .25098 .501961 .501961 rg (# other operations not requiring a lock here) Tj T* ET +Q +Q +Q +Q +Q +q +1 0 0 1 62.69291 623.8236 cm +q +BT 1 0 0 1 0 16.82 Tm .905868 Tw 12 TL /F1 10 Tf 0 0 0 rg (Each call to ) Tj /F5 10 Tf (write ) Tj /F1 10 Tf (will create a new writer thread, but there will be no synchronization problems since) Tj T* 0 Tw /F5 10 Tf (write ) Tj /F1 10 Tf (is locked.) Tj T* ET +Q +Q +q +1 0 0 1 62.69291 458.6236 cm +q +q +1 0 0 1 0 0 cm +q +1 0 0 1 6.6 6.6 cm +q +.662745 .662745 .662745 RG +.5 w +.960784 .960784 .862745 rg +n -6 -6 468.6898 156 re B* +Q +q +BT 1 0 0 1 0 137.71 Tm 12 TL /F5 10 Tf .4 .4 .4 rg (>) Tj (>) Tj (>) Tj 0 0 0 rg ( ) Tj (write) Tj (\() Tj .729412 .129412 .129412 rg ("data1") Tj 0 0 0 rg (\)) Tj T* .4 .4 .4 rg (<) Tj 0 0 0 rg (Thread) Tj (\() Tj (write) Tj .4 .4 .4 rg (-) Tj (1) Tj 0 0 0 rg (,) Tj ( ) Tj (started) Tj .4 .4 .4 rg (...) Tj 0 0 0 rg (\)) Tj .4 .4 .4 rg (>) Tj 0 0 0 rg T* T* .4 .4 .4 rg (>) Tj (>) Tj (>) Tj 0 0 0 rg ( ) Tj (time) Tj .4 .4 .4 rg (.) Tj 0 0 0 rg (sleep) Tj (\() Tj .4 .4 .4 rg (.) Tj (1) Tj 0 0 0 rg (\)) Tj ( ) Tj /F7 10 Tf .25098 .501961 .501961 rg (# wait a bit, so we are sure data2 is written after data1) Tj /F5 10 Tf 0 0 0 rg T* T* .4 .4 .4 rg (>) Tj (>) Tj (>) Tj 0 0 0 rg ( ) Tj (write) Tj (\() Tj .729412 .129412 .129412 rg ("data2") Tj 0 0 0 rg (\)) Tj T* .4 .4 .4 rg (<) Tj 0 0 0 rg (Thread) Tj (\() Tj (write) Tj .4 .4 .4 rg (-) Tj (2) Tj 0 0 0 rg (,) Tj ( ) Tj (started) Tj .4 .4 .4 rg (...) Tj 0 0 0 rg (\)) Tj .4 .4 .4 rg (>) Tj 0 0 0 rg T* T* .4 .4 .4 rg (>) Tj (>) Tj (>) Tj 0 0 0 rg ( ) Tj (time) Tj .4 .4 .4 rg (.) Tj 0 0 0 rg (sleep) Tj (\() Tj .4 .4 .4 rg (2) Tj 0 0 0 rg (\)) Tj ( ) Tj /F7 10 Tf .25098 .501961 .501961 rg (# wait for the writers to complete) Tj /F5 10 Tf 0 0 0 rg T* T* .4 .4 .4 rg (>) Tj (>) Tj (>) Tj 0 0 0 rg ( ) Tj /F3 10 Tf 0 .501961 0 rg (print) Tj /F5 10 Tf 0 0 0 rg (\() Tj (datalist) Tj (\)) Tj T* ([) Tj .729412 .129412 .129412 rg ('data1') Tj 0 0 0 rg (,) Tj ( ) Tj .729412 .129412 .129412 rg ('data2') Tj 0 0 0 rg (]) Tj T* ET +Q +Q +Q +Q +Q +q +1 0 0 1 62.69291 425.6236 cm +q +BT 1 0 0 1 0 8.435 Tm 21 TL /F2 17.5 Tf 0 0 0 rg (The ) Tj /F3 17.5 Tf (FunctionMaker ) Tj /F2 17.5 Tf (class) Tj T* ET +Q +Q +q +1 0 0 1 62.69291 359.6236 cm +q +BT 1 0 0 1 0 52.82 Tm 2.241412 Tw 12 TL /F1 10 Tf 0 0 0 rg (You may wonder about how the functionality of the ) Tj /F5 10 Tf (decorator ) Tj /F1 10 Tf (module is implemented. The basic) Tj T* 0 Tw 1.545868 Tw (building block is a ) Tj /F5 10 Tf (FunctionMaker ) Tj /F1 10 Tf (class which is able to generate on the fly functions with a given) Tj T* 0 Tw .047485 Tw (name and signature from a function template passed as a string. Generally speaking, you should not need) Tj T* 0 Tw 1.164983 Tw (to resort to ) Tj /F5 10 Tf (FunctionMaker ) Tj /F1 10 Tf (when writing ordinary decorators, but it is handy in some circumstances.) Tj T* 0 Tw (You will see an example shortly, in the implementation of a cool decorator utility \() Tj /F5 10 Tf (decorator_apply) Tj /F1 10 Tf (\).) Tj T* ET +Q +Q +q +1 0 0 1 62.69291 317.6236 cm +q +BT 1 0 0 1 0 28.82 Tm .414597 Tw 12 TL /F5 10 Tf 0 0 0 rg (FunctionMaker ) Tj /F1 10 Tf (provides a ) Tj /F5 10 Tf (.create ) Tj /F1 10 Tf (classmethod which takes as input the name, signature, and body) Tj T* 0 Tw .632927 Tw (of the function we want to generate as well as the execution environment were the function is generated) Tj T* 0 Tw (by ) Tj /F5 10 Tf (exec) Tj /F1 10 Tf (. Here is an example:) Tj T* ET +Q +Q +q +1 0 0 1 62.69291 224.4236 cm +q +q +1 0 0 1 0 0 cm +q +1 0 0 1 6.6 6.6 cm +q +.662745 .662745 .662745 RG +.5 w +.960784 .960784 .862745 rg +n -6 -6 468.6898 84 re B* +Q +q +BT 1 0 0 1 0 65.71 Tm 12 TL /F5 10 Tf .4 .4 .4 rg (>) Tj (>) Tj (>) Tj 0 0 0 rg ( ) Tj /F3 10 Tf 0 .501961 0 rg (def) Tj /F5 10 Tf 0 0 0 rg ( ) Tj 0 0 1 rg (f) Tj 0 0 0 rg (\() Tj .4 .4 .4 rg (*) Tj 0 0 0 rg (args) Tj (,) Tj ( ) Tj .4 .4 .4 rg (**) Tj 0 0 0 rg (kw) Tj (\):) Tj ( ) Tj /F7 10 Tf .25098 .501961 .501961 rg (# a function with a generic signature) Tj /F5 10 Tf 0 0 0 rg T* .4 .4 .4 rg (...) Tj 0 0 0 rg ( ) Tj /F3 10 Tf 0 .501961 0 rg (print) Tj /F5 10 Tf 0 0 0 rg (\() Tj (args) Tj (,) Tj ( ) Tj (kw) Tj (\)) Tj T* T* .4 .4 .4 rg (>) Tj (>) Tj (>) Tj 0 0 0 rg ( ) Tj (f1) Tj ( ) Tj .4 .4 .4 rg (=) Tj 0 0 0 rg ( ) Tj (FunctionMaker) Tj .4 .4 .4 rg (.) Tj 0 0 0 rg (create) Tj (\() Tj .729412 .129412 .129412 rg ('f1\(a, b\)') Tj 0 0 0 rg (,) Tj ( ) Tj .729412 .129412 .129412 rg ('f\(a, b\)') Tj 0 0 0 rg (,) Tj ( ) Tj 0 .501961 0 rg (dict) Tj 0 0 0 rg (\() Tj (f) Tj .4 .4 .4 rg (=) Tj 0 0 0 rg (f) Tj (\)\)) Tj T* .4 .4 .4 rg (>) Tj (>) Tj (>) Tj 0 0 0 rg ( ) Tj (f1) Tj (\() Tj .4 .4 .4 rg (1) Tj 0 0 0 rg (,) Tj .4 .4 .4 rg (2) Tj 0 0 0 rg (\)) Tj T* (\() Tj .4 .4 .4 rg (1) Tj 0 0 0 rg (,) Tj ( ) Tj .4 .4 .4 rg (2) Tj 0 0 0 rg (\)) Tj ( ) Tj ({}) Tj T* ET +Q +Q +Q +Q +Q +q +1 0 0 1 62.69291 192.4236 cm +q +BT 1 0 0 1 0 16.82 Tm .226654 Tw 12 TL /F1 10 Tf 0 0 0 rg (It is important to notice that the function body is interpolated before being executed, so be careful with the) Tj T* 0 Tw /F5 10 Tf (% ) Tj /F1 10 Tf (sign!) Tj T* ET +Q +Q +q +1 0 0 1 62.69291 150.4236 cm +q +BT 1 0 0 1 0 28.82 Tm 1.995433 Tw 12 TL /F5 10 Tf 0 0 0 rg (FunctionMaker.create ) Tj /F1 10 Tf (also accepts keyword arguments and such arguments are attached to the) Tj T* 0 Tw 1.64686 Tw (resulting function. This is useful if you want to set some function attributes, for instance the docstring) Tj T* 0 Tw /F5 10 Tf (__doc__) Tj /F1 10 Tf (.) Tj T* ET +Q +Q +q +1 0 0 1 62.69291 108.4236 cm +q +BT 1 0 0 1 0 28.82 Tm .605318 Tw 12 TL /F1 10 Tf 0 0 0 rg (For debugging/introspection purposes it may be useful to see the source code of the generated function;) Tj T* 0 Tw 2.246235 Tw (to do that, just pass the flag ) Tj /F5 10 Tf (addsource=True ) Tj /F1 10 Tf (and a ) Tj /F5 10 Tf (__source__ ) Tj /F1 10 Tf (attribute will be added to the) Tj T* 0 Tw (generated function:) Tj T* ET +Q +Q + +endstream + +endobj +% 'R89': class PDFStream +89 0 obj +% page stream +<< /Length 7605 >> +stream +1 0 0 1 0 0 cm BT /F1 12 Tf 14.4 TL ET +q +1 0 0 1 62.69291 679.8236 cm +q +q +1 0 0 1 0 0 cm +q +1 0 0 1 6.6 6.6 cm +q +.662745 .662745 .662745 RG +.5 w +.960784 .960784 .862745 rg +n -6 -6 468.6898 84 re B* +Q +q +BT 1 0 0 1 0 65.71 Tm 12 TL /F5 10 Tf .4 .4 .4 rg (>) Tj (>) Tj (>) Tj 0 0 0 rg ( ) Tj (f1) Tj ( ) Tj .4 .4 .4 rg (=) Tj 0 0 0 rg ( ) Tj (FunctionMaker) Tj .4 .4 .4 rg (.) Tj 0 0 0 rg (create) Tj (\() Tj T* .4 .4 .4 rg (...) Tj 0 0 0 rg ( ) Tj .729412 .129412 .129412 rg ('f1\(a, b\)') Tj 0 0 0 rg (,) Tj ( ) Tj .729412 .129412 .129412 rg ('f\(a, b\)') Tj 0 0 0 rg (,) Tj ( ) Tj 0 .501961 0 rg (dict) Tj 0 0 0 rg (\() Tj (f) Tj .4 .4 .4 rg (=) Tj 0 0 0 rg (f) Tj (\),) Tj ( ) Tj (addsource) Tj .4 .4 .4 rg (=) Tj 0 .501961 0 rg (True) Tj 0 0 0 rg (\)) Tj T* .4 .4 .4 rg (>) Tj (>) Tj (>) Tj 0 0 0 rg ( ) Tj /F3 10 Tf 0 .501961 0 rg (print) Tj /F5 10 Tf 0 0 0 rg (\() Tj (f1) Tj .4 .4 .4 rg (.) Tj 0 0 0 rg (__source__) Tj (\)) Tj T* /F3 10 Tf 0 .501961 0 rg (def) Tj /F5 10 Tf 0 0 0 rg ( ) Tj 0 0 1 rg (f1) Tj 0 0 0 rg (\() Tj (a) Tj (,) Tj ( ) Tj (b) Tj (\):) Tj T* ( ) Tj (f) Tj (\() Tj (a) Tj (,) Tj ( ) Tj (b) Tj (\)) Tj T* .4 .4 .4 rg (<) Tj 0 0 0 rg (BLANKLINE) Tj .4 .4 .4 rg (>) Tj T* ET +Q +Q +Q +Q +Q +q +1 0 0 1 62.69291 539.8236 cm +q +BT 1 0 0 1 0 124.82 Tm .870651 Tw 12 TL /F5 10 Tf 0 0 0 rg (FunctionMaker.create ) Tj /F1 10 Tf (can take as first argument a string, as in the examples before, or a function.) Tj T* 0 Tw .224985 Tw (This is the most common usage, since typically you want to decorate a pre-existing function. A framework) Tj T* 0 Tw 1.606136 Tw (author may want to use directly ) Tj /F5 10 Tf (FunctionMaker.create ) Tj /F1 10 Tf (instead of ) Tj /F5 10 Tf (decorator) Tj /F1 10 Tf (, since it gives you) Tj T* 0 Tw 1.36686 Tw (direct access to the body of the generated function. For instance, suppose you want to instrument the) Tj T* 0 Tw .372209 Tw /F5 10 Tf (__init__ ) Tj /F1 10 Tf (methods of a set of classes, by preserving their signature \(such use case is not made up; this) Tj T* 0 Tw .673828 Tw (is done in SQAlchemy and in other frameworks\). When the first argument of ) Tj /F5 10 Tf (FunctionMaker.create) Tj T* 0 Tw 3.405814 Tw /F1 10 Tf (is a function, a ) Tj /F5 10 Tf (FunctionMaker ) Tj /F1 10 Tf (object is instantiated internally, with attributes ) Tj /F5 10 Tf (args) Tj /F1 10 Tf (, ) Tj /F5 10 Tf (varargs) Tj /F1 10 Tf (,) Tj T* 0 Tw 5.509982 Tw /F5 10 Tf (keywords ) Tj /F1 10 Tf (and ) Tj /F5 10 Tf (defaults ) Tj /F1 10 Tf (which are the the return values of the standard library function) Tj T* 0 Tw .561318 Tw /F5 10 Tf (inspect.getargspec) Tj /F1 10 Tf (. For each argument in the ) Tj /F5 10 Tf (args ) Tj /F1 10 Tf (\(which is a list of strings containing the names) Tj T* 0 Tw 1.599985 Tw (of the mandatory arguments\) an attribute ) Tj /F5 10 Tf (arg0) Tj /F1 10 Tf (, ) Tj /F5 10 Tf (arg1) Tj /F1 10 Tf (, ..., ) Tj /F5 10 Tf (argN ) Tj /F1 10 Tf (is also generated. Finally, there is a) Tj T* 0 Tw /F5 10 Tf (signature ) Tj /F1 10 Tf (attribute, a string with the signature of the original function.) Tj T* ET +Q +Q +q +1 0 0 1 62.69291 461.8236 cm +q +BT 1 0 0 1 0 64.82 Tm 4.63311 Tw 12 TL /F1 10 Tf 0 0 0 rg (Notice that while I do not have plans to change or remove the functionality provided in the) Tj T* 0 Tw 1.00936 Tw /F5 10 Tf (FunctionMaker ) Tj /F1 10 Tf (class, I do not guarantee that it will stay unchanged forever. For instance, right now I) Tj T* 0 Tw .791318 Tw (am using the traditional string interpolation syntax for function templates, but Python 2.6 and Python 3.0) Tj T* 0 Tw .712093 Tw (provide a newer interpolation syntax and I may use the new syntax in the future. On the other hand, the) Tj T* 0 Tw .639985 Tw (functionality provided by ) Tj /F5 10 Tf (decorator ) Tj /F1 10 Tf (has been there from version 0.1 and it is guaranteed to stay there) Tj T* 0 Tw (forever.) Tj T* ET +Q +Q +q +1 0 0 1 62.69291 428.8236 cm +q +BT 1 0 0 1 0 8.435 Tm 21 TL /F2 17.5 Tf 0 0 0 rg (Getting the source code) Tj T* ET +Q +Q +q +1 0 0 1 62.69291 350.8236 cm +q +BT 1 0 0 1 0 64.82 Tm 5.045529 Tw 12 TL /F1 10 Tf 0 0 0 rg (Internally ) Tj /F5 10 Tf (FunctionMaker.create ) Tj /F1 10 Tf (uses ) Tj /F5 10 Tf (exec ) Tj /F1 10 Tf (to generate the decorated function. Therefore) Tj T* 0 Tw 2.542126 Tw /F5 10 Tf (inspect.getsource ) Tj /F1 10 Tf (will not work for decorated functions. That means that the usual '??' trick in) Tj T* 0 Tw 2.163059 Tw (IPython will give you the \(right on the spot\) message ) Tj /F5 10 Tf (Dynamically generated function. No) Tj T* 0 Tw .563314 Tw (source code available) Tj /F1 10 Tf (. In the past I have considered this acceptable, since ) Tj /F5 10 Tf (inspect.getsource) Tj T* 0 Tw 1.790697 Tw /F1 10 Tf (does not really work even with regular decorators. In that case ) Tj /F5 10 Tf (inspect.getsource ) Tj /F1 10 Tf (gives you the) Tj T* 0 Tw (wrapper source code which is probably not what you want:) Tj T* ET +Q +Q +q +1 0 0 1 62.69291 281.6236 cm +q +q +1 0 0 1 0 0 cm +q +1 0 0 1 6.6 6.6 cm +q +.662745 .662745 .662745 RG +.5 w +.960784 .960784 .862745 rg +n -6 -6 468.6898 60 re B* +Q +q +BT 1 0 0 1 0 41.71 Tm 12 TL /F3 10 Tf 0 .501961 0 rg (def) Tj /F5 10 Tf 0 0 0 rg ( ) Tj 0 0 1 rg (identity_dec) Tj 0 0 0 rg (\() Tj (func) Tj (\):) Tj T* ( ) Tj /F3 10 Tf 0 .501961 0 rg (def) Tj /F5 10 Tf 0 0 0 rg ( ) Tj 0 0 1 rg (wrapper) Tj 0 0 0 rg (\() Tj .4 .4 .4 rg (*) Tj 0 0 0 rg (args) Tj (,) Tj ( ) Tj .4 .4 .4 rg (**) Tj 0 0 0 rg (kw) Tj (\):) Tj T* ( ) Tj /F3 10 Tf 0 .501961 0 rg (return) Tj /F5 10 Tf 0 0 0 rg ( ) Tj (func) Tj (\() Tj .4 .4 .4 rg (*) Tj 0 0 0 rg (args) Tj (,) Tj ( ) Tj .4 .4 .4 rg (**) Tj 0 0 0 rg (kw) Tj (\)) Tj T* ( ) Tj /F3 10 Tf 0 .501961 0 rg (return) Tj /F5 10 Tf 0 0 0 rg ( ) Tj (wrapper) Tj T* ET +Q +Q +Q +Q +Q +q +1 0 0 1 62.69291 176.4236 cm +q +q +1 0 0 1 0 0 cm +q +1 0 0 1 6.6 6.6 cm +q +.662745 .662745 .662745 RG +.5 w +.960784 .960784 .862745 rg +n -6 -6 468.6898 96 re B* +Q +q +BT 1 0 0 1 0 77.71 Tm 12 TL /F5 10 Tf .666667 .133333 1 rg (@identity_dec) Tj 0 0 0 rg T* /F3 10 Tf 0 .501961 0 rg (def) Tj /F5 10 Tf 0 0 0 rg ( ) Tj 0 0 1 rg (example) Tj 0 0 0 rg (\(\):) Tj ( ) Tj /F3 10 Tf 0 .501961 0 rg (pass) Tj /F5 10 Tf 0 0 0 rg T* T* .4 .4 .4 rg (>) Tj (>) Tj (>) Tj 0 0 0 rg ( ) Tj /F3 10 Tf 0 .501961 0 rg (print) Tj /F5 10 Tf 0 0 0 rg (\() Tj (inspect) Tj .4 .4 .4 rg (.) Tj 0 0 0 rg (getsource) Tj (\() Tj (example) Tj (\)\)) Tj T* ( ) Tj /F3 10 Tf 0 .501961 0 rg (def) Tj /F5 10 Tf 0 0 0 rg ( ) Tj 0 0 1 rg (wrapper) Tj 0 0 0 rg (\() Tj .4 .4 .4 rg (*) Tj 0 0 0 rg (args) Tj (,) Tj ( ) Tj .4 .4 .4 rg (**) Tj 0 0 0 rg (kw) Tj (\):) Tj T* ( ) Tj /F3 10 Tf 0 .501961 0 rg (return) Tj /F5 10 Tf 0 0 0 rg ( ) Tj (func) Tj (\() Tj .4 .4 .4 rg (*) Tj 0 0 0 rg (args) Tj (,) Tj ( ) Tj .4 .4 .4 rg (**) Tj 0 0 0 rg (kw) Tj (\)) Tj T* .4 .4 .4 rg (<) Tj 0 0 0 rg (BLANKLINE) Tj .4 .4 .4 rg (>) Tj T* ET +Q +Q +Q +Q +Q +q +1 0 0 1 62.69291 120.4236 cm +q +BT 1 0 0 1 0 40.82 Tm 1.471235 Tw 12 TL /F1 10 Tf 0 0 0 rg (\(see bug report ) Tj 0 0 .501961 rg (1764286 ) Tj 0 0 0 rg (for an explanation of what is happening\). Unfortunately the bug is still there,) Tj T* 0 Tw 1.541235 Tw (even in Python 2.6 and 3.0. There is however a workaround. The decorator module adds an attribute) Tj T* 0 Tw .103984 Tw /F5 10 Tf (.undecorated ) Tj /F1 10 Tf (to the decorated function, containing a reference to the original function. The easy way to) Tj T* 0 Tw (get the source code is to call ) Tj /F5 10 Tf (inspect.getsource ) Tj /F1 10 Tf (on the undecorated function:) Tj T* ET +Q +Q + +endstream + +endobj +% 'R90': class PDFStream +90 0 obj +% page stream +<< /Length 7166 >> +stream +1 0 0 1 0 0 cm BT /F1 12 Tf 14.4 TL ET +q +1 0 0 1 62.69291 667.8236 cm +q +q +1 0 0 1 0 0 cm +q +1 0 0 1 6.6 6.6 cm +q +.662745 .662745 .662745 RG +.5 w +.960784 .960784 .862745 rg +n -6 -6 468.6898 96 re B* +Q +q +BT 1 0 0 1 0 77.71 Tm 12 TL /F5 10 Tf .4 .4 .4 rg (>) Tj (>) Tj (>) Tj 0 0 0 rg ( ) Tj /F3 10 Tf 0 .501961 0 rg (print) Tj /F5 10 Tf 0 0 0 rg (\() Tj (inspect) Tj .4 .4 .4 rg (.) Tj 0 0 0 rg (getsource) Tj (\() Tj (factorial) Tj .4 .4 .4 rg (.) Tj 0 0 0 rg (undecorated) Tj (\)\)) Tj T* .666667 .133333 1 rg (@tail_recursive) Tj 0 0 0 rg T* /F3 10 Tf 0 .501961 0 rg (def) Tj /F5 10 Tf 0 0 0 rg ( ) Tj 0 0 1 rg (factorial) Tj 0 0 0 rg (\() Tj (n) Tj (,) Tj ( ) Tj (acc) Tj .4 .4 .4 rg (=) Tj (1) Tj 0 0 0 rg (\):) Tj T* ( ) Tj .729412 .129412 .129412 rg ("The good old factorial") Tj 0 0 0 rg T* ( ) Tj /F3 10 Tf 0 .501961 0 rg (if) Tj /F5 10 Tf 0 0 0 rg ( ) Tj (n) Tj ( ) Tj .4 .4 .4 rg (==) Tj 0 0 0 rg ( ) Tj .4 .4 .4 rg (0) Tj 0 0 0 rg (:) Tj ( ) Tj /F3 10 Tf 0 .501961 0 rg (return) Tj /F5 10 Tf 0 0 0 rg ( ) Tj (acc) Tj T* ( ) Tj /F3 10 Tf 0 .501961 0 rg (return) Tj /F5 10 Tf 0 0 0 rg ( ) Tj (factorial) Tj (\() Tj (n) Tj .4 .4 .4 rg (-) Tj (1) Tj 0 0 0 rg (,) Tj ( ) Tj (n) Tj .4 .4 .4 rg (*) Tj 0 0 0 rg (acc) Tj (\)) Tj T* .4 .4 .4 rg (<) Tj 0 0 0 rg (BLANKLINE) Tj .4 .4 .4 rg (>) Tj T* ET +Q +Q +Q +Q +Q +q +1 0 0 1 62.69291 634.8236 cm +q +BT 1 0 0 1 0 8.435 Tm 21 TL /F2 17.5 Tf 0 0 0 rg (Dealing with third party decorators) Tj T* ET +Q +Q +q +1 0 0 1 62.69291 580.8236 cm +q +BT 1 0 0 1 0 40.82 Tm .321654 Tw 12 TL /F1 10 Tf 0 0 0 rg (Sometimes you find on the net some cool decorator that you would like to include in your code. However,) Tj T* 0 Tw .50061 Tw (more often than not the cool decorator is not signature-preserving. Therefore you may want an easy way) Tj T* 0 Tw 1.814597 Tw (to upgrade third party decorators to signature-preserving decorators without having to rewrite them in) Tj T* 0 Tw (terms of ) Tj /F5 10 Tf (decorator) Tj /F1 10 Tf (. You can use a ) Tj /F5 10 Tf (FunctionMaker ) Tj /F1 10 Tf (to implement that functionality as follows:) Tj T* ET +Q +Q +q +1 0 0 1 62.69291 463.6236 cm +q +q +1 0 0 1 0 0 cm +q +1 0 0 1 6.6 6.6 cm +q +.662745 .662745 .662745 RG +.5 w +.960784 .960784 .862745 rg +n -6 -6 468.6898 108 re B* +Q +q +BT 1 0 0 1 0 89.71 Tm 12 TL /F3 10 Tf 0 .501961 0 rg (def) Tj /F5 10 Tf 0 0 0 rg ( ) Tj 0 0 1 rg (decorator_apply) Tj 0 0 0 rg (\() Tj (dec) Tj (,) Tj ( ) Tj (func) Tj (\):) Tj T* ( ) Tj /F7 10 Tf .729412 .129412 .129412 rg (""") Tj T* ( Decorate a function by preserving the signature even if dec) Tj T* ( is not a signature-preserving decorator.) Tj T* ( """) Tj /F5 10 Tf 0 0 0 rg T* ( ) Tj /F3 10 Tf 0 .501961 0 rg (return) Tj /F5 10 Tf 0 0 0 rg ( ) Tj (FunctionMaker) Tj .4 .4 .4 rg (.) Tj 0 0 0 rg (create) Tj (\() Tj T* ( ) Tj (func) Tj (,) Tj ( ) Tj .729412 .129412 .129412 rg ('return decorated\() Tj /F3 10 Tf .733333 .4 .533333 rg (%\(signature\)s) Tj /F5 10 Tf .729412 .129412 .129412 rg (\)') Tj 0 0 0 rg (,) Tj T* ( ) Tj 0 .501961 0 rg (dict) Tj 0 0 0 rg (\() Tj (decorated) Tj .4 .4 .4 rg (=) Tj 0 0 0 rg (dec) Tj (\() Tj (func) Tj (\)\),) Tj ( ) Tj (undecorated) Tj .4 .4 .4 rg (=) Tj 0 0 0 rg (func) Tj (\)) Tj T* ET +Q +Q +Q +Q +Q +q +1 0 0 1 62.69291 431.6236 cm +q +BT 1 0 0 1 0 16.82 Tm .698314 Tw 12 TL /F5 10 Tf 0 0 0 rg (decorator_apply ) Tj /F1 10 Tf (sets the attribute ) Tj /F5 10 Tf (.undecorated ) Tj /F1 10 Tf (of the generated function to the original function,) Tj T* 0 Tw (so that you can get the right source code.) Tj T* ET +Q +Q +q +1 0 0 1 62.69291 389.6236 cm +q +BT 1 0 0 1 0 28.82 Tm .13104 Tw 12 TL /F1 10 Tf 0 0 0 rg (Notice that I am not providing this functionality in the ) Tj /F5 10 Tf (decorator ) Tj /F1 10 Tf (module directly since I think it is best to) Tj T* 0 Tw 2.070751 Tw (rewrite the decorator rather than adding an additional level of indirection. However, practicality beats) Tj T* 0 Tw (purity, so you can add ) Tj /F5 10 Tf (decorator_apply ) Tj /F1 10 Tf (to your toolbox and use it if you need to.) Tj T* ET +Q +Q +q +1 0 0 1 62.69291 335.6236 cm +q +BT 1 0 0 1 0 40.82 Tm 1.74881 Tw 12 TL /F1 10 Tf 0 0 0 rg (In order to give an example of usage of ) Tj /F5 10 Tf (decorator_apply) Tj /F1 10 Tf (, I will show a pretty slick decorator that) Tj T* 0 Tw 1.276651 Tw (converts a tail-recursive function in an iterative function. I have shamelessly stolen the basic idea from) Tj T* 0 Tw 43.62829 Tw (Kay Schluehr's recipe in the Python Cookbook,) Tj T* 0 Tw 0 0 .501961 rg (http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/496691) Tj 0 0 0 rg (.) Tj T* ET +Q +Q +q +1 0 0 1 62.69291 86.42362 cm +q +q +1 0 0 1 0 0 cm +q +1 0 0 1 6.6 6.6 cm +q +.662745 .662745 .662745 RG +.5 w +.960784 .960784 .862745 rg +n -6 -6 468.6898 240 re B* +Q +q +BT 1 0 0 1 0 221.71 Tm 12 TL /F3 10 Tf 0 .501961 0 rg (class) Tj /F5 10 Tf 0 0 0 rg ( ) Tj /F3 10 Tf 0 0 1 rg (TailRecursive) Tj /F5 10 Tf 0 0 0 rg (\() Tj 0 .501961 0 rg (object) Tj 0 0 0 rg (\):) Tj T* ( ) Tj /F7 10 Tf .729412 .129412 .129412 rg (""") Tj T* ( tail_recursive decorator based on Kay Schluehr's recipe) Tj T* ( http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/496691) Tj T* ( with improvements by me and George Sakkis.) Tj T* ( """) Tj /F5 10 Tf 0 0 0 rg T* T* ( ) Tj /F3 10 Tf 0 .501961 0 rg (def) Tj /F5 10 Tf 0 0 0 rg ( ) Tj 0 0 1 rg (__init__) Tj 0 0 0 rg (\() Tj 0 .501961 0 rg (self) Tj 0 0 0 rg (,) Tj ( ) Tj (func) Tj (\):) Tj T* ( ) Tj 0 .501961 0 rg (self) Tj .4 .4 .4 rg (.) Tj 0 0 0 rg (func) Tj ( ) Tj .4 .4 .4 rg (=) Tj 0 0 0 rg ( ) Tj (func) Tj T* ( ) Tj 0 .501961 0 rg (self) Tj .4 .4 .4 rg (.) Tj 0 0 0 rg (firstcall) Tj ( ) Tj .4 .4 .4 rg (=) Tj 0 0 0 rg ( ) Tj 0 .501961 0 rg (True) Tj 0 0 0 rg T* ( ) Tj 0 .501961 0 rg (self) Tj .4 .4 .4 rg (.) Tj 0 0 0 rg (CONTINUE) Tj ( ) Tj .4 .4 .4 rg (=) Tj 0 0 0 rg ( ) Tj 0 .501961 0 rg (object) Tj 0 0 0 rg (\(\)) Tj ( ) Tj /F7 10 Tf .25098 .501961 .501961 rg (# sentinel) Tj /F5 10 Tf 0 0 0 rg T* T* ( ) Tj /F3 10 Tf 0 .501961 0 rg (def) Tj /F5 10 Tf 0 0 0 rg ( ) Tj 0 0 1 rg (__call__) Tj 0 0 0 rg (\() Tj 0 .501961 0 rg (self) Tj 0 0 0 rg (,) Tj ( ) Tj .4 .4 .4 rg (*) Tj 0 0 0 rg (args) Tj (,) Tj ( ) Tj .4 .4 .4 rg (**) Tj 0 0 0 rg (kwd) Tj (\):) Tj T* ( ) Tj (CONTINUE) Tj ( ) Tj .4 .4 .4 rg (=) Tj 0 0 0 rg ( ) Tj 0 .501961 0 rg (self) Tj .4 .4 .4 rg (.) Tj 0 0 0 rg (CONTINUE) Tj T* ( ) Tj /F3 10 Tf 0 .501961 0 rg (if) Tj /F5 10 Tf 0 0 0 rg ( ) Tj 0 .501961 0 rg (self) Tj .4 .4 .4 rg (.) Tj 0 0 0 rg (firstcall) Tj (:) Tj T* ( ) Tj (func) Tj ( ) Tj .4 .4 .4 rg (=) Tj 0 0 0 rg ( ) Tj 0 .501961 0 rg (self) Tj .4 .4 .4 rg (.) Tj 0 0 0 rg (func) Tj T* ( ) Tj 0 .501961 0 rg (self) Tj .4 .4 .4 rg (.) Tj 0 0 0 rg (firstcall) Tj ( ) Tj .4 .4 .4 rg (=) Tj 0 0 0 rg ( ) Tj 0 .501961 0 rg (False) Tj 0 0 0 rg T* ( ) Tj /F3 10 Tf 0 .501961 0 rg (try) Tj /F5 10 Tf 0 0 0 rg (:) Tj T* ( ) Tj /F3 10 Tf 0 .501961 0 rg (while) Tj /F5 10 Tf 0 0 0 rg ( ) Tj 0 .501961 0 rg (True) Tj 0 0 0 rg (:) Tj T* ET +Q +Q +Q +Q +Q + +endstream + +endobj +% 'R91': class PDFStream +91 0 obj +% page stream +<< /Length 6779 >> +stream +1 0 0 1 0 0 cm BT /F1 12 Tf 14.4 TL ET +q +1 0 0 1 62.69291 631.8236 cm +q +q +1 0 0 1 0 0 cm +q +1 0 0 1 6.6 6.6 cm +q +.662745 .662745 .662745 RG +.5 w +.960784 .960784 .862745 rg +n -6 -6 468.6898 132 re B* +Q +q +BT 1 0 0 1 0 113.71 Tm 12 TL /F5 10 Tf 0 0 0 rg ( ) Tj (result) Tj ( ) Tj .4 .4 .4 rg (=) Tj 0 0 0 rg ( ) Tj (func) Tj (\() Tj .4 .4 .4 rg (*) Tj 0 0 0 rg (args) Tj (,) Tj ( ) Tj .4 .4 .4 rg (**) Tj 0 0 0 rg (kwd) Tj (\)) Tj T* ( ) Tj /F3 10 Tf 0 .501961 0 rg (if) Tj /F5 10 Tf 0 0 0 rg ( ) Tj (result) Tj ( ) Tj /F3 10 Tf .666667 .133333 1 rg (is) Tj /F5 10 Tf 0 0 0 rg ( ) Tj (CONTINUE) Tj (:) Tj ( ) Tj /F7 10 Tf .25098 .501961 .501961 rg (# update arguments) Tj /F5 10 Tf 0 0 0 rg T* ( ) Tj (args) Tj (,) Tj ( ) Tj (kwd) Tj ( ) Tj .4 .4 .4 rg (=) Tj 0 0 0 rg ( ) Tj 0 .501961 0 rg (self) Tj .4 .4 .4 rg (.) Tj 0 0 0 rg (argskwd) Tj T* ( ) Tj /F3 10 Tf 0 .501961 0 rg (else) Tj /F5 10 Tf 0 0 0 rg (:) Tj ( ) Tj /F7 10 Tf .25098 .501961 .501961 rg (# last call) Tj /F5 10 Tf 0 0 0 rg T* ( ) Tj /F3 10 Tf 0 .501961 0 rg (return) Tj /F5 10 Tf 0 0 0 rg ( ) Tj (result) Tj T* ( ) Tj /F3 10 Tf 0 .501961 0 rg (finally) Tj /F5 10 Tf 0 0 0 rg (:) Tj T* ( ) Tj 0 .501961 0 rg (self) Tj .4 .4 .4 rg (.) Tj 0 0 0 rg (firstcall) Tj ( ) Tj .4 .4 .4 rg (=) Tj 0 0 0 rg ( ) Tj 0 .501961 0 rg (True) Tj 0 0 0 rg T* ( ) Tj /F3 10 Tf 0 .501961 0 rg (else) Tj /F5 10 Tf 0 0 0 rg (:) Tj ( ) Tj /F7 10 Tf .25098 .501961 .501961 rg (# return the arguments of the tail call) Tj /F5 10 Tf 0 0 0 rg T* ( ) Tj 0 .501961 0 rg (self) Tj .4 .4 .4 rg (.) Tj 0 0 0 rg (argskwd) Tj ( ) Tj .4 .4 .4 rg (=) Tj 0 0 0 rg ( ) Tj (args) Tj (,) Tj ( ) Tj (kwd) Tj T* ( ) Tj /F3 10 Tf 0 .501961 0 rg (return) Tj /F5 10 Tf 0 0 0 rg ( ) Tj (CONTINUE) Tj T* ET +Q +Q +Q +Q +Q +q +1 0 0 1 62.69291 611.8236 cm +q +0 0 0 rg +BT 1 0 0 1 0 4.82 Tm /F1 10 Tf 12 TL (Here the decorator is implemented as a class returning callable objects.) Tj T* ET +Q +Q +q +1 0 0 1 62.69291 566.6236 cm +q +q +1 0 0 1 0 0 cm +q +1 0 0 1 6.6 6.6 cm +q +.662745 .662745 .662745 RG +.5 w +.960784 .960784 .862745 rg +n -6 -6 468.6898 36 re B* +Q +q +BT 1 0 0 1 0 17.71 Tm 12 TL /F3 10 Tf 0 .501961 0 rg (def) Tj /F5 10 Tf 0 0 0 rg ( ) Tj 0 0 1 rg (tail_recursive) Tj 0 0 0 rg (\() Tj (func) Tj (\):) Tj T* ( ) Tj /F3 10 Tf 0 .501961 0 rg (return) Tj /F5 10 Tf 0 0 0 rg ( ) Tj (decorator_apply) Tj (\() Tj (TailRecursive) Tj (,) Tj ( ) Tj (func) Tj (\)) Tj T* ET +Q +Q +Q +Q +Q +q +1 0 0 1 62.69291 546.6236 cm +q +0 0 0 rg +BT 1 0 0 1 0 4.82 Tm /F1 10 Tf 12 TL (Here is how you apply the upgraded decorator to the good old factorial:) Tj T* ET +Q +Q +q +1 0 0 1 62.69291 465.4236 cm +q +q +1 0 0 1 0 0 cm +q +1 0 0 1 6.6 6.6 cm +q +.662745 .662745 .662745 RG +.5 w +.960784 .960784 .862745 rg +n -6 -6 468.6898 72 re B* +Q +q +BT 1 0 0 1 0 53.71 Tm 12 TL /F5 10 Tf .666667 .133333 1 rg (@tail_recursive) Tj 0 0 0 rg T* /F3 10 Tf 0 .501961 0 rg (def) Tj /F5 10 Tf 0 0 0 rg ( ) Tj 0 0 1 rg (factorial) Tj 0 0 0 rg (\() Tj (n) Tj (,) Tj ( ) Tj (acc) Tj .4 .4 .4 rg (=) Tj (1) Tj 0 0 0 rg (\):) Tj T* ( ) Tj .729412 .129412 .129412 rg ("The good old factorial") Tj 0 0 0 rg T* ( ) Tj /F3 10 Tf 0 .501961 0 rg (if) Tj /F5 10 Tf 0 0 0 rg ( ) Tj (n) Tj ( ) Tj .4 .4 .4 rg (==) Tj 0 0 0 rg ( ) Tj .4 .4 .4 rg (0) Tj 0 0 0 rg (:) Tj ( ) Tj /F3 10 Tf 0 .501961 0 rg (return) Tj /F5 10 Tf 0 0 0 rg ( ) Tj (acc) Tj T* ( ) Tj /F3 10 Tf 0 .501961 0 rg (return) Tj /F5 10 Tf 0 0 0 rg ( ) Tj (factorial) Tj (\() Tj (n) Tj .4 .4 .4 rg (-) Tj (1) Tj 0 0 0 rg (,) Tj ( ) Tj (n) Tj .4 .4 .4 rg (*) Tj 0 0 0 rg (acc) Tj (\)) Tj T* ET +Q +Q +Q +Q +Q +q +1 0 0 1 62.69291 420.2236 cm +q +q +1 0 0 1 0 0 cm +q +1 0 0 1 6.6 6.6 cm +q +.662745 .662745 .662745 RG +.5 w +.960784 .960784 .862745 rg +n -6 -6 468.6898 36 re B* +Q +q +BT 1 0 0 1 0 17.71 Tm 12 TL /F5 10 Tf .4 .4 .4 rg (>) Tj (>) Tj (>) Tj 0 0 0 rg ( ) Tj /F3 10 Tf 0 .501961 0 rg (print) Tj /F5 10 Tf 0 0 0 rg (\() Tj (factorial) Tj (\() Tj .4 .4 .4 rg (4) Tj 0 0 0 rg (\)\)) Tj T* .4 .4 .4 rg (24) Tj T* ET +Q +Q +Q +Q +Q +q +1 0 0 1 62.69291 364.2236 cm +q +BT 1 0 0 1 0 40.82 Tm .188935 Tw 12 TL /F1 10 Tf 0 0 0 rg (This decorator is pretty impressive, and should give you some food for your mind ;\) Notice that there is no) Tj T* 0 Tw 1.339983 Tw (recursion limit now, and you can easily compute ) Tj /F5 10 Tf (factorial\(1001\) ) Tj /F1 10 Tf (or larger without filling the stack) Tj T* 0 Tw .909431 Tw (frame. Notice also that the decorator will not work on functions which are not tail recursive, such as the) Tj T* 0 Tw (following) Tj T* ET +Q +Q +q +1 0 0 1 62.69291 307.0236 cm +q +q +1 0 0 1 0 0 cm +q +1 0 0 1 6.6 6.6 cm +q +.662745 .662745 .662745 RG +.5 w +.960784 .960784 .862745 rg +n -6 -6 468.6898 48 re B* +Q +q +BT 1 0 0 1 0 29.71 Tm 12 TL /F3 10 Tf 0 .501961 0 rg (def) Tj /F5 10 Tf 0 0 0 rg ( ) Tj 0 0 1 rg (fact) Tj 0 0 0 rg (\() Tj (n) Tj (\):) Tj ( ) Tj /F7 10 Tf .25098 .501961 .501961 rg (# this is not tail-recursive) Tj /F5 10 Tf 0 0 0 rg T* ( ) Tj /F3 10 Tf 0 .501961 0 rg (if) Tj /F5 10 Tf 0 0 0 rg ( ) Tj (n) Tj ( ) Tj .4 .4 .4 rg (==) Tj 0 0 0 rg ( ) Tj .4 .4 .4 rg (0) Tj 0 0 0 rg (:) Tj ( ) Tj /F3 10 Tf 0 .501961 0 rg (return) Tj /F5 10 Tf 0 0 0 rg ( ) Tj .4 .4 .4 rg (1) Tj 0 0 0 rg T* ( ) Tj /F3 10 Tf 0 .501961 0 rg (return) Tj /F5 10 Tf 0 0 0 rg ( ) Tj (n) Tj ( ) Tj .4 .4 .4 rg (*) Tj 0 0 0 rg ( ) Tj (fact) Tj (\() Tj (n) Tj .4 .4 .4 rg (-) Tj (1) Tj 0 0 0 rg (\)) Tj T* ET +Q +Q +Q +Q +Q +q +1 0 0 1 62.69291 275.0236 cm +q +0 0 0 rg +BT 1 0 0 1 0 16.82 Tm /F1 10 Tf 12 TL .541098 Tw (\(reminder: a function is tail recursive if it either returns a value without making a recursive call, or returns) Tj T* 0 Tw (directly the result of a recursive call\).) Tj T* ET +Q +Q +q +1 0 0 1 62.69291 242.0236 cm +q +BT 1 0 0 1 0 8.435 Tm 21 TL /F2 17.5 Tf 0 0 0 rg (Caveats and limitations) Tj T* ET +Q +Q +q +1 0 0 1 62.69291 212.0236 cm +q +0 0 0 rg +BT 1 0 0 1 0 16.82 Tm /F1 10 Tf 12 TL .474987 Tw (The first thing you should be aware of, it the fact that decorators have a performance penalty. The worse) Tj T* 0 Tw (case is shown by the following example:) Tj T* ET +Q +Q +q +1 0 0 1 62.69291 82.82362 cm +q +q +1 0 0 1 0 0 cm +q +1 0 0 1 6.6 6.6 cm +q +.662745 .662745 .662745 RG +.5 w +.960784 .960784 .862745 rg +n -6 -6 468.6898 120 re B* +Q +q +0 0 0 rg +BT 1 0 0 1 0 101.71 Tm /F5 10 Tf 12 TL ($ cat performance.sh) Tj T* (python3 -m timeit -s ") Tj T* (from decorator import decorator) Tj T* T* (@decorator) Tj T* (def do_nothing\(func, *args, **kw\):) Tj T* ( return func\(*args, **kw\)) Tj T* T* (@do_nothing) Tj T* ET +Q +Q +Q +Q +Q + +endstream + +endobj +% 'R92': class PDFStream +92 0 obj +% page stream +<< /Length 6628 >> +stream +1 0 0 1 0 0 cm BT /F1 12 Tf 14.4 TL ET +q +1 0 0 1 62.69291 655.8236 cm +q +q +1 0 0 1 0 0 cm +q +1 0 0 1 6.6 6.6 cm +q +.662745 .662745 .662745 RG +.5 w +.960784 .960784 .862745 rg +n -6 -6 468.6898 108 re B* +Q +q +0 0 0 rg +BT 1 0 0 1 0 89.71 Tm /F5 10 Tf 12 TL (def f\(\):) Tj T* ( pass) Tj T* (" "f\(\)") Tj T* T* (python3 -m timeit -s ") Tj T* (def f\(\):) Tj T* ( pass) Tj T* (" "f\(\)") Tj T* ET +Q +Q +Q +Q +Q +q +1 0 0 1 62.69291 623.8236 cm +q +BT 1 0 0 1 0 16.82 Tm .266235 Tw 12 TL /F1 10 Tf 0 0 0 rg (On my MacBook, using the ) Tj /F5 10 Tf (do_nothing ) Tj /F1 10 Tf (decorator instead of the plain function is more than three times) Tj T* 0 Tw (slower:) Tj T* ET +Q +Q +q +1 0 0 1 62.69291 566.6236 cm +q +q +1 0 0 1 0 0 cm +q +1 0 0 1 6.6 6.6 cm +q +.662745 .662745 .662745 RG +.5 w +.960784 .960784 .862745 rg +n -6 -6 468.6898 48 re B* +Q +q +0 0 0 rg +BT 1 0 0 1 0 29.71 Tm /F5 10 Tf 12 TL ($ bash performance.sh) Tj T* (1000000 loops, best of 3: 0.669 usec per loop) Tj T* (1000000 loops, best of 3: 0.181 usec per loop) Tj T* ET +Q +Q +Q +Q +Q +q +1 0 0 1 62.69291 522.6236 cm +q +BT 1 0 0 1 0 28.82 Tm 1.25832 Tw 12 TL /F1 10 Tf 0 0 0 rg (It should be noted that a real life function would probably do something more useful than ) Tj /F5 10 Tf (f ) Tj /F1 10 Tf (here, and) Tj T* 0 Tw .91811 Tw (therefore in real life the performance penalty could be completely negligible. As always, the only way to) Tj T* 0 Tw (know if there is a penalty in your specific use case is to measure it.) Tj T* ET +Q +Q +q +1 0 0 1 62.69291 492.6236 cm +q +0 0 0 rg +BT 1 0 0 1 0 16.82 Tm /F1 10 Tf 12 TL .867984 Tw (You should be aware that decorators will make your tracebacks longer and more difficult to understand.) Tj T* 0 Tw (Consider this example:) Tj T* ET +Q +Q +q +1 0 0 1 62.69291 435.4236 cm +q +q +1 0 0 1 0 0 cm +q +1 0 0 1 6.6 6.6 cm +q +.662745 .662745 .662745 RG +.5 w +.960784 .960784 .862745 rg +n -6 -6 468.6898 48 re B* +Q +q +BT 1 0 0 1 0 29.71 Tm 12 TL /F5 10 Tf .4 .4 .4 rg (>) Tj (>) Tj (>) Tj 0 0 0 rg ( ) Tj .666667 .133333 1 rg (@trace) Tj 0 0 0 rg T* .4 .4 .4 rg (...) Tj 0 0 0 rg ( ) Tj /F3 10 Tf 0 .501961 0 rg (def) Tj /F5 10 Tf 0 0 0 rg ( ) Tj 0 0 1 rg (f) Tj 0 0 0 rg (\(\):) Tj T* .4 .4 .4 rg (...) Tj 0 0 0 rg ( ) Tj .4 .4 .4 rg (1) Tj (/) Tj (0) Tj T* ET +Q +Q +Q +Q +Q +q +1 0 0 1 62.69291 403.4236 cm +q +BT 1 0 0 1 0 16.82 Tm .583318 Tw 12 TL /F1 10 Tf 0 0 0 rg (Calling ) Tj /F5 10 Tf (f\(\) ) Tj /F1 10 Tf (will give you a ) Tj /F5 10 Tf (ZeroDivisionError) Tj /F1 10 Tf (, but since the function is decorated the traceback will) Tj T* 0 Tw (be longer:) Tj T* ET +Q +Q +q +1 0 0 1 62.69291 274.2236 cm +q +q +1 0 0 1 0 0 cm +q +1 0 0 1 6.6 6.6 cm +q +.662745 .662745 .662745 RG +.5 w +.960784 .960784 .862745 rg +n -6 -6 468.6898 120 re B* +Q +q +BT 1 0 0 1 0 101.71 Tm 12 TL /F5 10 Tf .4 .4 .4 rg (>) Tj (>) Tj (>) Tj 0 0 0 rg ( ) Tj (f) Tj (\(\)) Tj T* (Traceback) Tj ( ) Tj (\() Tj (most) Tj ( ) Tj (recent) Tj ( ) Tj (call) Tj ( ) Tj (last) Tj (\):) Tj T* ( ) Tj .4 .4 .4 rg (...) Tj 0 0 0 rg T* ( ) Tj (File) Tj ( ) Tj .729412 .129412 .129412 rg (") Tj (<) Tj (string) Tj (>) Tj (") Tj 0 0 0 rg (,) Tj ( ) Tj (line) Tj ( ) Tj .4 .4 .4 rg (2) Tj 0 0 0 rg (,) Tj ( ) Tj /F3 10 Tf .666667 .133333 1 rg (in) Tj /F5 10 Tf 0 0 0 rg ( ) Tj (f) Tj T* ( ) Tj (File) Tj ( ) Tj .729412 .129412 .129412 rg (") Tj (<) Tj (doctest __main__[22]) Tj (>) Tj (") Tj 0 0 0 rg (,) Tj ( ) Tj (line) Tj ( ) Tj .4 .4 .4 rg (4) Tj 0 0 0 rg (,) Tj ( ) Tj /F3 10 Tf .666667 .133333 1 rg (in) Tj /F5 10 Tf 0 0 0 rg ( ) Tj (trace) Tj T* ( ) Tj /F3 10 Tf 0 .501961 0 rg (return) Tj /F5 10 Tf 0 0 0 rg ( ) Tj (f) Tj (\() Tj .4 .4 .4 rg (*) Tj 0 0 0 rg (args) Tj (,) Tj ( ) Tj .4 .4 .4 rg (**) Tj 0 0 0 rg (kw) Tj (\)) Tj T* ( ) Tj (File) Tj ( ) Tj .729412 .129412 .129412 rg (") Tj (<) Tj (doctest __main__[51]) Tj (>) Tj (") Tj 0 0 0 rg (,) Tj ( ) Tj (line) Tj ( ) Tj .4 .4 .4 rg (3) Tj 0 0 0 rg (,) Tj ( ) Tj /F3 10 Tf .666667 .133333 1 rg (in) Tj /F5 10 Tf 0 0 0 rg ( ) Tj (f) Tj T* ( ) Tj .4 .4 .4 rg (1) Tj (/) Tj (0) Tj 0 0 0 rg T* /F3 10 Tf .823529 .254902 .227451 rg (ZeroDivisionError) Tj /F5 10 Tf 0 0 0 rg (:) Tj ( ) Tj 0 .501961 0 rg (int) Tj 0 0 0 rg ( ) Tj (division) Tj ( ) Tj /F3 10 Tf .666667 .133333 1 rg (or) Tj /F5 10 Tf 0 0 0 rg ( ) Tj (modulo) Tj ( ) Tj (by) Tj ( ) Tj (zero) Tj T* ET +Q +Q +Q +Q +Q +q +1 0 0 1 62.69291 206.2236 cm +q +BT 1 0 0 1 0 52.82 Tm 1.05528 Tw 12 TL /F1 10 Tf 0 0 0 rg (You see here the inner call to the decorator ) Tj /F5 10 Tf (trace) Tj /F1 10 Tf (, which calls ) Tj /F5 10 Tf (f\(*args, **kw\)) Tj /F1 10 Tf (, and a reference to) Tj T* 0 Tw .265868 Tw /F5 10 Tf (File ") Tj (<) Tj (string) Tj (>) Tj (", line 2, in f) Tj /F1 10 Tf (. This latter reference is due to the fact that internally the decorator) Tj T* 0 Tw 2.053318 Tw (module uses ) Tj /F5 10 Tf (exec ) Tj /F1 10 Tf (to generate the decorated function. Notice that ) Tj /F5 10 Tf (exec ) Tj /F1 10 Tf (is ) Tj /F6 10 Tf (not ) Tj /F1 10 Tf (responsibile for the) Tj T* 0 Tw 1.507485 Tw (performance penalty, since is the called ) Tj /F6 10 Tf (only once ) Tj /F1 10 Tf (at function decoration time, and not every time the) Tj T* 0 Tw (decorated function is called.) Tj T* ET +Q +Q +q +1 0 0 1 62.69291 128.2236 cm +q +BT 1 0 0 1 0 64.82 Tm .932209 Tw 12 TL /F1 10 Tf 0 0 0 rg (At present, there is no clean way to avoid ) Tj /F5 10 Tf (exec) Tj /F1 10 Tf (. A clean solution would require to change the CPython) Tj T* 0 Tw .777485 Tw (implementation of functions and add an hook to make it possible to change their signature directly. That) Tj T* 0 Tw .74186 Tw (could happen in future versions of Python \(see PEP ) Tj 0 0 .501961 rg (362) Tj 0 0 0 rg (\) and then the decorator module would become) Tj T* 0 Tw 2.385318 Tw (obsolete. However, at present, even in Python 3.1 it is impossible to change the function signature) Tj T* 0 Tw .931751 Tw (directly, therefore the ) Tj /F5 10 Tf (decorator ) Tj /F1 10 Tf (module is still useful. Actually, this is one of the main reasons why I) Tj T* 0 Tw (keep maintaining the module and releasing new versions.) Tj T* ET +Q +Q +q +1 0 0 1 62.69291 86.22362 cm +q +BT 1 0 0 1 0 28.82 Tm 1.043828 Tw 12 TL /F1 10 Tf 0 0 0 rg (In the present implementation, decorators generated by ) Tj /F5 10 Tf (decorator ) Tj /F1 10 Tf (can only be used on user-defined) Tj T* 0 Tw .152485 Tw (Python functions or methods, not on generic callable objects, nor on built-in functions, due to limitations of) Tj T* 0 Tw (the ) Tj /F5 10 Tf (inspect ) Tj /F1 10 Tf (module in the standard library.) Tj T* ET +Q +Q + +endstream + +endobj +% 'R93': class PDFStream +93 0 obj +% page stream +<< /Length 7976 >> +stream +1 0 0 1 0 0 cm BT /F1 12 Tf 14.4 TL ET +q +1 0 0 1 62.69291 741.0236 cm +q +BT 1 0 0 1 0 16.82 Tm .785777 Tw 12 TL /F1 10 Tf 0 0 0 rg (There is a restriction on the names of the arguments: for instance, if try to call an argument ) Tj /F5 10 Tf (_call_ ) Tj /F1 10 Tf (or) Tj T* 0 Tw /F5 10 Tf (_func_ ) Tj /F1 10 Tf (you will get a ) Tj /F5 10 Tf (NameError) Tj /F1 10 Tf (:) Tj T* ET +Q +Q +q +1 0 0 1 62.69291 623.8236 cm +q +q +1 0 0 1 0 0 cm +q +1 0 0 1 6.6 6.6 cm +q +.662745 .662745 .662745 RG +.5 w +.960784 .960784 .862745 rg +n -6 -6 468.6898 108 re B* +Q +q +BT 1 0 0 1 0 89.71 Tm 12 TL /F5 10 Tf .4 .4 .4 rg (>) Tj (>) Tj (>) Tj 0 0 0 rg ( ) Tj .666667 .133333 1 rg (@trace) Tj 0 0 0 rg T* .4 .4 .4 rg (...) Tj 0 0 0 rg ( ) Tj /F3 10 Tf 0 .501961 0 rg (def) Tj /F5 10 Tf 0 0 0 rg ( ) Tj 0 0 1 rg (f) Tj 0 0 0 rg (\() Tj (_func_) Tj (\):) Tj ( ) Tj /F3 10 Tf 0 .501961 0 rg (print) Tj /F5 10 Tf 0 0 0 rg (\() Tj (f) Tj (\)) Tj T* .4 .4 .4 rg (...) Tj 0 0 0 rg T* (Traceback) Tj ( ) Tj (\() Tj (most) Tj ( ) Tj (recent) Tj ( ) Tj (call) Tj ( ) Tj (last) Tj (\):) Tj T* ( ) Tj .4 .4 .4 rg (...) Tj 0 0 0 rg T* /F3 10 Tf .823529 .254902 .227451 rg (NameError) Tj /F5 10 Tf 0 0 0 rg (:) Tj ( ) Tj (_func_) Tj ( ) Tj /F3 10 Tf .666667 .133333 1 rg (is) Tj /F5 10 Tf 0 0 0 rg ( ) Tj (overridden) Tj ( ) Tj /F3 10 Tf .666667 .133333 1 rg (in) Tj /F5 10 Tf 0 0 0 rg T* /F3 10 Tf 0 .501961 0 rg (def) Tj /F5 10 Tf 0 0 0 rg ( ) Tj 0 0 1 rg (f) Tj 0 0 0 rg (\() Tj (_func_) Tj (\):) Tj T* ( ) Tj /F3 10 Tf 0 .501961 0 rg (return) Tj /F5 10 Tf 0 0 0 rg ( ) Tj (_call_) Tj (\() Tj (_func_) Tj (,) Tj ( ) Tj (_func_) Tj (\)) Tj T* ET +Q +Q +Q +Q +Q +q +1 0 0 1 62.69291 591.8236 cm +q +BT 1 0 0 1 0 16.82 Tm 1.533318 Tw 12 TL /F1 10 Tf 0 0 0 rg (Finally, the implementation is such that the decorated function contains a ) Tj /F6 10 Tf (copy ) Tj /F1 10 Tf (of the original function) Tj T* 0 Tw (dictionary \() Tj /F5 10 Tf (vars\(decorated_f\) is not vars\(f\)) Tj /F1 10 Tf (\):) Tj T* ET +Q +Q +q +1 0 0 1 62.69291 438.6236 cm +q +q +1 0 0 1 0 0 cm +q +1 0 0 1 6.6 6.6 cm +q +.662745 .662745 .662745 RG +.5 w +.960784 .960784 .862745 rg +n -6 -6 468.6898 144 re B* +Q +q +BT 1 0 0 1 0 125.71 Tm 12 TL /F5 10 Tf .4 .4 .4 rg (>) Tj (>) Tj (>) Tj 0 0 0 rg ( ) Tj /F3 10 Tf 0 .501961 0 rg (def) Tj /F5 10 Tf 0 0 0 rg ( ) Tj 0 0 1 rg (f) Tj 0 0 0 rg (\(\):) Tj ( ) Tj /F3 10 Tf 0 .501961 0 rg (pass) Tj /F5 10 Tf 0 0 0 rg ( ) Tj /F7 10 Tf .25098 .501961 .501961 rg (# the original function) Tj /F5 10 Tf 0 0 0 rg T* .4 .4 .4 rg (>) Tj (>) Tj (>) Tj 0 0 0 rg ( ) Tj (f) Tj .4 .4 .4 rg (.) Tj 0 0 0 rg (attr1) Tj ( ) Tj .4 .4 .4 rg (=) Tj 0 0 0 rg ( ) Tj .729412 .129412 .129412 rg ("something") Tj 0 0 0 rg ( ) Tj /F7 10 Tf .25098 .501961 .501961 rg (# setting an attribute) Tj /F5 10 Tf 0 0 0 rg T* .4 .4 .4 rg (>) Tj (>) Tj (>) Tj 0 0 0 rg ( ) Tj (f) Tj .4 .4 .4 rg (.) Tj 0 0 0 rg (attr2) Tj ( ) Tj .4 .4 .4 rg (=) Tj 0 0 0 rg ( ) Tj .729412 .129412 .129412 rg ("something else") Tj 0 0 0 rg ( ) Tj /F7 10 Tf .25098 .501961 .501961 rg (# setting another attribute) Tj /F5 10 Tf 0 0 0 rg T* T* .4 .4 .4 rg (>) Tj (>) Tj (>) Tj 0 0 0 rg ( ) Tj (traced_f) Tj ( ) Tj .4 .4 .4 rg (=) Tj 0 0 0 rg ( ) Tj (trace) Tj (\() Tj (f) Tj (\)) Tj ( ) Tj /F7 10 Tf .25098 .501961 .501961 rg (# the decorated function) Tj /F5 10 Tf 0 0 0 rg T* T* .4 .4 .4 rg (>) Tj (>) Tj (>) Tj 0 0 0 rg ( ) Tj (traced_f) Tj .4 .4 .4 rg (.) Tj 0 0 0 rg (attr1) Tj T* .729412 .129412 .129412 rg ('something') Tj 0 0 0 rg T* .4 .4 .4 rg (>) Tj (>) Tj (>) Tj 0 0 0 rg ( ) Tj (traced_f) Tj .4 .4 .4 rg (.) Tj 0 0 0 rg (attr2) Tj ( ) Tj .4 .4 .4 rg (=) Tj 0 0 0 rg ( ) Tj .729412 .129412 .129412 rg ("something different") Tj 0 0 0 rg ( ) Tj /F7 10 Tf .25098 .501961 .501961 rg (# setting attr) Tj /F5 10 Tf 0 0 0 rg T* .4 .4 .4 rg (>) Tj (>) Tj (>) Tj 0 0 0 rg ( ) Tj (f) Tj .4 .4 .4 rg (.) Tj 0 0 0 rg (attr2) Tj ( ) Tj /F7 10 Tf .25098 .501961 .501961 rg (# the original attribute did not change) Tj /F5 10 Tf 0 0 0 rg T* .729412 .129412 .129412 rg ('something else') Tj T* ET +Q +Q +Q +Q +Q +q +1 0 0 1 62.69291 405.6236 cm +q +BT 1 0 0 1 0 8.435 Tm 21 TL /F2 17.5 Tf 0 0 0 rg (Compatibility notes) Tj T* ET +Q +Q +q +1 0 0 1 62.69291 339.6236 cm +q +BT 1 0 0 1 0 52.82 Tm 1.19686 Tw 12 TL /F1 10 Tf 0 0 0 rg (Version 3.2 is the first version of the ) Tj /F5 10 Tf (decorator ) Tj /F1 10 Tf (module to officially support Python 3.0. Actually, the) Tj T* 0 Tw 1.33311 Tw (module has supported Python 3.0 from the beginning, via the ) Tj /F5 10 Tf (2to3 ) Tj /F1 10 Tf (conversion tool, but this step has) Tj T* 0 Tw 2.714269 Tw (been now integrated in the build process, thanks to the ) Tj 0 0 .501961 rg (distribute ) Tj 0 0 0 rg (project, the Python 3-compatible) Tj T* 0 Tw 1.961412 Tw (replacement of easy_install. The hard work \(for me\) has been converting the documentation and the) Tj T* 0 Tw (doctests. This has been possible only now that ) Tj 0 0 .501961 rg (docutils ) Tj 0 0 0 rg (and ) Tj 0 0 .501961 rg (pygments ) Tj 0 0 0 rg (have been ported to Python 3.) Tj T* ET +Q +Q +q +1 0 0 1 62.69291 261.6236 cm +q +BT 1 0 0 1 0 64.82 Tm 1.19561 Tw 12 TL /F1 10 Tf 0 0 0 rg (The ) Tj /F5 10 Tf (decorator ) Tj /F1 10 Tf (module ) Tj /F6 10 Tf (per se ) Tj /F1 10 Tf (does not contain any change, apart from the removal of the functions) Tj T* 0 Tw 1.348314 Tw /F5 10 Tf (get_info ) Tj /F1 10 Tf (and ) Tj /F5 10 Tf (new_wrapper) Tj /F1 10 Tf (, which have been deprecated for years. ) Tj /F5 10 Tf (get_info ) Tj /F1 10 Tf (has been removed) Tj T* 0 Tw .921654 Tw (since it was little used and since it had to be changed anyway to work with Python 3.0; ) Tj /F5 10 Tf (new_wrapper) Tj T* 0 Tw .609318 Tw /F1 10 Tf (has been removed since it was useless: its major use case \(converting signature changing decorators to) Tj T* 0 Tw .028443 Tw (signature preserving decorators\) has been subsumed by ) Tj /F5 10 Tf (decorator_apply ) Tj /F1 10 Tf (and the other use case can) Tj T* 0 Tw (be managed with the ) Tj /F5 10 Tf (FunctionMaker) Tj /F1 10 Tf (.) Tj T* ET +Q +Q +q +1 0 0 1 62.69291 195.6236 cm +q +BT 1 0 0 1 0 52.82 Tm 1.329213 Tw 12 TL /F1 10 Tf 0 0 0 rg (There are a few changes in the documentation: I removed the ) Tj /F5 10 Tf (decorator_factory ) Tj /F1 10 Tf (example, which) Tj T* 0 Tw 2.562927 Tw (was confusing some of my users, and I removed the part about exotic signatures in the Python 3) Tj T* 0 Tw 2.20061 Tw (documentation, since Python 3 does not support them. Notice that there is no support for Python 3) Tj T* 0 Tw 1.163984 Tw 0 0 .501961 rg (function annotations ) Tj 0 0 0 rg (since it seems premature at the moment, when most people are still using Python) Tj T* 0 Tw (2.X.) Tj T* ET +Q +Q +q +1 0 0 1 62.69291 129.6236 cm +q +BT 1 0 0 1 0 52.82 Tm .942651 Tw 12 TL /F1 10 Tf 0 0 0 rg (Finally ) Tj /F5 10 Tf (decorator ) Tj /F1 10 Tf (cannot be used as a class decorator and the ) Tj 0 0 .501961 rg (functionality introduced in version 2.3) Tj T* 0 Tw .241163 Tw 0 0 0 rg (has been removed. That means that in order to define decorator factories with classes you need to define) Tj T* 0 Tw 1.122126 Tw (the ) Tj /F5 10 Tf (__call__ ) Tj /F1 10 Tf (method explicitly \(no magic anymore\). All these changes should not cause any trouble,) Tj T* 0 Tw .601163 Tw (since they were all rarely used features. Should you have any trouble, you can always downgrade to the) Tj T* 0 Tw (2.3 version.) Tj T* ET +Q +Q +q +1 0 0 1 62.69291 87.62362 cm +q +BT 1 0 0 1 0 28.82 Tm .196098 Tw 12 TL /F1 10 Tf 0 0 0 rg (The examples shown here have been tested with Python 2.6. Python 2.4 is also supported - of course the ) Tj T* 0 Tw 1.649398 Tw (examples requiring the ) Tj /F5 10 Tf (with ) Tj /F1 10 Tf (statement will not work there. Python 2.5 works fine, but if you run the ) Tj T* 0 Tw 1.41784 Tw (examples in the interactive interpreter you will notice a few differences since ) Tj /F5 10 Tf (getargspec ) Tj /F1 10 Tf (returns an) Tj T* 0 Tw ET +Q +Q + +endstream + +endobj +% 'R94': class PDFStream +94 0 obj +% page stream +<< /Length 2641 >> +stream +1 0 0 1 0 0 cm BT /F1 12 Tf 14.4 TL ET +q +1 0 0 1 62.69291 741.0236 cm +q +BT 1 0 0 1 0 16.82 Tm .909982 Tw 12 TL /F5 10 Tf 0 0 0 rg (ArgSpec ) Tj /F1 10 Tf (namedtuple instead of a regular tuple. That means that running the file ) Tj /F5 10 Tf (documentation.py) Tj T* 0 Tw /F1 10 Tf (under Python 2.5 will print a few errors, but they are not serious.) Tj T* ET +Q +Q +q +1 0 0 1 62.69291 708.0236 cm +q +BT 1 0 0 1 0 8.435 Tm 21 TL /F2 17.5 Tf 0 0 0 rg (LICENCE) Tj T* ET +Q +Q +q +1 0 0 1 62.69291 678.0236 cm +q +0 0 0 rg +BT 1 0 0 1 0 16.82 Tm /F1 10 Tf 12 TL 1.328555 Tw (Redistribution and use in source and binary forms, with or without modification, are permitted provided) Tj T* 0 Tw (that the following conditions are met:) Tj T* ET +Q +Q +q +1 0 0 1 62.69291 392.8236 cm +q +q +1 0 0 1 0 0 cm +q +1 0 0 1 6.6 6.6 cm +q +.662745 .662745 .662745 RG +.5 w +.960784 .960784 .862745 rg +n -6 -6 468.6898 276 re B* +Q +q +0 0 0 rg +BT 1 0 0 1 0 257.71 Tm /F5 10 Tf 12 TL (Copyright \(c\) 2005, Michele Simionato) Tj T* (All rights reserved.) Tj T* T* (Redistributions of source code must retain the above copyright) Tj T* (notice, this list of conditions and the following disclaimer.) Tj T* (Redistributions in bytecode form must reproduce the above copyright) Tj T* (notice, this list of conditions and the following disclaimer in) Tj T* (the documentation and/or other materials provided with the) Tj T* (distribution.) Tj T* T* (THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS) Tj T* ("AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT) Tj T* (LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR) Tj T* (A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT) Tj T* (HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,) Tj T* (INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES \(INCLUDING,) Tj T* (BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS) Tj T* (OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION\) HOWEVER CAUSED AND) Tj T* (ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR) Tj T* (TORT \(INCLUDING NEGLIGENCE OR OTHERWISE\) ARISING IN ANY WAY OUT OF THE) Tj T* (USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH) Tj T* (DAMAGE.) Tj T* ET +Q +Q +Q +Q +Q +q +1 0 0 1 62.69291 360.8236 cm +q +0 0 0 rg +BT 1 0 0 1 0 16.82 Tm /F1 10 Tf 12 TL .407132 Tw (If you use this software and you are happy with it, consider sending me a note, just to gratify my ego. On) Tj T* 0 Tw (the other hand, if you use this software and you are unhappy with it, send me a patch!) Tj T* ET +Q +Q + +endstream + +endobj +% 'R95': class PDFPageLabels +95 0 obj +% Document Root +<< /Nums [ 0 + 96 0 R + 1 + 97 0 R + 2 + 98 0 R + 3 + 99 0 R + 4 + 100 0 R + 5 + 101 0 R + 6 + 102 0 R + 7 + 103 0 R + 8 + 104 0 R + 9 + 105 0 R + 10 + 106 0 R + 11 + 107 0 R + 12 + 108 0 R + 13 + 109 0 R ] >> +endobj +% 'R96': class PDFPageLabel +96 0 obj +% None +<< /S /D + /St 1 >> +endobj +% 'R97': class PDFPageLabel +97 0 obj +% None +<< /S /D + /St 2 >> +endobj +% 'R98': class PDFPageLabel +98 0 obj +% None +<< /S /D + /St 3 >> +endobj +% 'R99': class PDFPageLabel +99 0 obj +% None +<< /S /D + /St 4 >> +endobj +% 'R100': class PDFPageLabel +100 0 obj +% None +<< /S /D + /St 5 >> +endobj +% 'R101': class PDFPageLabel +101 0 obj +% None +<< /S /D + /St 6 >> +endobj +% 'R102': class PDFPageLabel +102 0 obj +% None +<< /S /D + /St 7 >> +endobj +% 'R103': class PDFPageLabel +103 0 obj +% None +<< /S /D + /St 8 >> +endobj +% 'R104': class PDFPageLabel +104 0 obj +% None +<< /S /D + /St 9 >> +endobj +% 'R105': class PDFPageLabel +105 0 obj +% None +<< /S /D + /St 10 >> +endobj +% 'R106': class PDFPageLabel +106 0 obj +% None +<< /S /D + /St 11 >> +endobj +% 'R107': class PDFPageLabel +107 0 obj +% None +<< /S /D + /St 12 >> +endobj +% 'R108': class PDFPageLabel +108 0 obj +% None +<< /S /D + /St 13 >> +endobj +% 'R109': class PDFPageLabel +109 0 obj +% None +<< /S /D + /St 14 >> +endobj +xref +0 110 +0000000000 65535 f +0000000113 00000 n +0000000283 00000 n +0000000448 00000 n +0000000623 00000 n +0000000794 00000 n +0000000975 00000 n +0000001227 00000 n +0000001476 00000 n +0000001650 00000 n +0000001891 00000 n +0000002133 00000 n +0000002375 00000 n +0000002617 00000 n +0000002859 00000 n +0000003101 00000 n +0000003344 00000 n +0000003587 00000 n +0000003830 00000 n +0000004073 00000 n +0000004315 00000 n +0000004557 00000 n +0000004799 00000 n +0000005041 00000 n +0000005284 00000 n +0000005527 00000 n +0000005770 00000 n +0000006013 00000 n +0000006256 00000 n +0000006499 00000 n +0000006742 00000 n +0000006985 00000 n +0000007228 00000 n +0000007471 00000 n +0000007714 00000 n +0000007957 00000 n +0000008200 00000 n +0000008427 00000 n +0000008988 00000 n +0000009183 00000 n +0000009439 00000 n +0000009630 00000 n +0000009890 00000 n +0000010200 00000 n +0000010480 00000 n +0000010760 00000 n +0000011040 00000 n +0000011320 00000 n +0000011600 00000 n +0000011895 00000 n +0000012135 00000 n +0000012451 00000 n +0000012719 00000 n +0000013021 00000 n +0000013316 00000 n +0000013561 00000 n +0000013877 00000 n +0000014135 00000 n +0000014387 00000 n +0000014627 00000 n +0000014887 00000 n +0000015194 00000 n +0000015532 00000 n +0000015813 00000 n +0000015972 00000 n +0000016221 00000 n +0000016347 00000 n +0000016520 00000 n +0000016707 00000 n +0000016907 00000 n +0000017095 00000 n +0000017288 00000 n +0000017487 00000 n +0000017670 00000 n +0000017851 00000 n +0000018050 00000 n +0000018250 00000 n +0000018462 00000 n +0000018662 00000 n +0000018858 00000 n +0000019010 00000 n +0000019236 00000 n +0000028440 00000 n +0000036177 00000 n +0000044258 00000 n +0000051529 00000 n +0000059939 00000 n +0000067642 00000 n +0000075047 00000 n +0000082428 00000 n +0000090134 00000 n +0000097401 00000 n +0000104281 00000 n +0000111010 00000 n +0000119087 00000 n +0000121833 00000 n +0000122109 00000 n +0000122186 00000 n +0000122263 00000 n +0000122340 00000 n +0000122418 00000 n +0000122497 00000 n +0000122576 00000 n +0000122655 00000 n +0000122734 00000 n +0000122813 00000 n +0000122893 00000 n +0000122973 00000 n +0000123053 00000 n +0000123133 00000 n +trailer +<< /ID + % ReportLab generated PDF document -- digest (http://www.reportlab.com) + [(\273\274\270\361\231\313i\315\035\242\307]\215 7M) (\273\274\270\361\231\313i\315\035\242\307]\215 7M)] + + /Info 64 0 R + /Root 63 0 R + /Size 110 >> +startxref +123182 +%%EOF diff --git a/documentation3.py b/documentation3.py index 259d0ba..94641ab 100644 --- a/documentation3.py +++ b/documentation3.py @@ -83,11 +83,11 @@ the function is called with the same input parameters the result is retrieved from the cache and not recomputed. There are many implementations of ``memoize`` in http://www.python.org/moin/PythonDecoratorLibrary, but they do not preserve the signature. -A simple implementation for Python 2.5 could be the following (notice +A simple implementation could be the following (notice that in general it is impossible to memoize correctly something that depends on non-hashable arguments): -$$memoize25 +$$memoize_uw Here we used the functools.update_wrapper_ utility, which has been added in Python 2.5 expressly to simplify the definition of decorators @@ -100,14 +100,14 @@ from the original function to the decorated function by hand). The implementation above works in the sense that the decorator can accept functions with generic signatures; unfortunately this implementation does *not* define a signature-preserving decorator, since in -general ``memoize25`` returns a function with a +general ``memoize_uw`` returns a function with a *different signature* from the original function. Consider for instance the following case: .. code-block:: python - >>> @memoize25 + >>> @memoize_uw ... def f1(x): ... time.sleep(1) # simulate some long computation ... return x @@ -160,7 +160,7 @@ At this point you can define your decorator as follows: $$memoize -The difference with respect to the Python 2.5 approach, which is based +The difference with respect to the ``memoize_uw`` approach, which is based on nested functions, is that the decorator module forces you to lift the inner function at the outer level (*flat is better than nested*). Moreover, you are forced to pass explicitly the function you want to @@ -685,12 +685,12 @@ Compatibility notes --------------------------------------------------------------- Version 3.2 is the first version of the ``decorator`` module to officially -support Python 3.0. Actually, the module has supported Python 3.0 from +support Python 3. Actually, the module has supported Python 3 from the beginning, via the ``2to3`` conversion tool, but this step has been now integrated in the build process, thanks to the distribute_ project, the Python 3-compatible replacement of easy_install. The hard work (for me) has been converting the documentation and the -doctests. This has been possibly only now that docutils_ and pygments_ +doctests. This has been possible only now that docutils_ and pygments_ have been ported to Python 3. The ``decorator`` module *per se* does not contain any change, apart @@ -722,11 +722,11 @@ downgrade to the 2.3 version. The examples shown here have been tested with Python 2.6. Python 2.4 is also supported - of course the examples requiring the ``with`` statement will not work there. Python 2.5 works fine, but if you -run the examples here in the interactive interpreter +run the examples in the interactive interpreter you will notice a few differences since ``getargspec`` returns an ``ArgSpec`` namedtuple instead of a regular tuple. That means that running the file -``documentation.py`` under Python 2.5 will a few errors, but +``documentation.py`` under Python 2.5 will print a few errors, but they are not serious. .. _functionality introduced in version 2.3: http://www.phyast.pitt.edu/~micheles/python/documentation.html#class-decorators-and-decorator-factories @@ -851,7 +851,7 @@ def identity_dec(func): @identity_dec def example(): pass -def memoize25(func): +def memoize_uw(func): func.cache = {} def memoize(*args, **kw): if kw: # frozenset is used to ensure hashability diff --git a/index.html b/index.html index 4f9912a..597a1fd 100644 --- a/index.html +++ b/index.html @@ -309,22 +309,39 @@ ul.auto-toc {

Dependencies:

The decorator module requires Python 2.4.

-

Installation:

+
+

Installation

+

If you are lazy, just perform

+

$ easy_install decorator

+

which will install just the module on your system. Notice that +Python 3 requires the easy_install version of the distribute project.

+

If you prefer to install the full distribution from source, including +the documentation, download the tarball, unpack it and run

$ python setup.py install

-

Testing:

+

in the main directory, possibly as superuser.

+
+
+

Testing

For Python 2.4, 2.5, 2.6, 2.7 run

$ python documentation.py

for Python 3.X run

$ python documentation3.py

You will see a few innocuous errors with Python 2.4 and 2.5, because some inner details such as the introduction of the ArgSpec namedtuple -and Thread.__repr__ changed. You may safely ignore them.

-

Notice:

-

You may get into trouble if in your system there is an older version +and Thread.__repr__ changed. You may safely ignore them. +Notice that you may run into trouble if in your system there is an older version of the decorator module; in such a case remove the old version.

-

Documentation:

-

There are two versions of the documentation, one for Python 2 and one -for Python 3 .

+
+
+

Documentation

+

There are various versions of the documentation:

+ +
-- cgit v1.2.1 From 3d346b8af0c20873c539bf8d15cfe4a5d52beae6 Mon Sep 17 00:00:00 2001 From: micheles Date: Sat, 22 May 2010 10:05:10 +0200 Subject: Fixed a few links --- README.txt | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/README.txt b/README.txt index 1fb5097..3e67bdb 100644 --- a/README.txt +++ b/README.txt @@ -53,7 +53,7 @@ There are various versions of the documentation: - `HTML version (Python 3)`_ - `PDF version (Python 3)`_ -.. _HTML version (Python 2): documentation.html -.. _PDF version (Python 2): documentation.pdf -.. _HTML version (Python 3): documentation3.html -.. _PDF version (Python 3): documentation3.pdf +.. _HTML version (Python 2): http://micheles.googlecode.com/hg/decorator/documentation.html +.. _PDF version (Python 2): http://micheles.googlecode.com/hg/decorator/documentation.pdf +.. _HTML version (Python 3): http://micheles.googlecode.com/hg/decorator/documentation3.html +.. _PDF version (Python 3): http://micheles.googlecode.com/hg/decorator/documentation3.pdf -- cgit v1.2.1 From 8b1d0bb809b716caf835b5df2382988fabf0242d Mon Sep 17 00:00:00 2001 From: micheles Date: Sat, 22 May 2010 14:23:05 +0200 Subject: Minor fixes --- MANIFEST.in | 1 + README.txt | 8 ++++++-- 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/MANIFEST.in b/MANIFEST.in index 5a305de..52e7659 100644 --- a/MANIFEST.in +++ b/MANIFEST.in @@ -1 +1,2 @@ +include documentation.py documentation3.py exclude Makefile diff --git a/README.txt b/README.txt index 3e67bdb..78bfce8 100644 --- a/README.txt +++ b/README.txt @@ -1,9 +1,13 @@ Decorator module ================= -Dependencies: -The decorator module requires Python 2.4. +:Author: Michele Simionato +:E-mail: michele.simionato@gmail.com +:Requires: Python 2.4+ +:Download page: http://pypi.python.org/pypi/decorator +:Installation: ``easy_install decorator`` +:License: BSD license Installation ------------- -- cgit v1.2.1 From 5bc8eb142c0deb5dc19e2db045b3e50b5cba2da7 Mon Sep 17 00:00:00 2001 From: micheles Date: Sat, 22 May 2010 14:29:43 +0200 Subject: Fixed the index.html --- index.html | 30 +++++++++++++++++++++++------- 1 file changed, 23 insertions(+), 7 deletions(-) diff --git a/index.html b/index.html index 597a1fd..403afc7 100644 --- a/index.html +++ b/index.html @@ -5,6 +5,7 @@ Decorator module +