Репозиторий Sisyphus
Последнее обновление: 1 октября 2023 | Пакетов: 18631 | Посещений: 37564409
en ru br
Репозитории ALT

Группа :: Разработка/Python
Пакет: python-module-decoratortools

 Главная   Изменения   Спек   Патчи   Исходники   Загрузить   Gear   Bugs and FR  Repocop 

pax_global_header00006660000000000000000000000064111663321100014504gustar00rootroot0000000000000052 comment=dd0caf5bdf1421ea9a8222f040b3f86cb3dd9904
python-module-decoratortools-1.7/000075500000000000000000000000001116633211000172165ustar00rootroot00000000000000python-module-decoratortools-1.7/.gear/000075500000000000000000000000001116633211000202125ustar00rootroot00000000000000python-module-decoratortools-1.7/.gear/rules000064400000000000000000000000071116633211000212640ustar00rootroot00000000000000tar: .
python-module-decoratortools-1.7/README.txt000075500000000000000000000737261116633211000207360ustar00rootroot00000000000000Class, Function, and Assignment Decorators, Metaclasses, and Related Tools
==========================================================================

Want to use decorators, but still need to support Python 2.3? Wish you could
have class decorators, decorate arbitrary assignments, or match decorated
function signatures to their original functions? Want to get metaclass
features without creating metaclasses? How about synchronized methods?

"DecoratorTools" gets you all of this and more. Some quick examples::

# Method decorator example
from peak.util.decorators import decorate

class Demo1(object):
decorate(classmethod) # equivalent to @classmethod
def example(cls):
print "hello from", cls


# Class decorator example
from peak.util.decorators import decorate_class

def my_class_decorator():
def decorator(cls):
print "decorating", cls
return cls
decorate_class(decorator)

class Demo2:
my_class_decorator()

# "decorating <class Demo2>" will be printed when execution gets here


Installing DecoratorTools (using ``"easy_install DecoratorTools"`` or
``"setup.py install"``) gives you access to the ``peak.util.decorators``
module. The tools in this module have been bundled for years inside of PEAK,
PyProtocols, RuleDispatch, and the zope.interface package, so they have been
widely used and tested. (Unit tests are also included, of course.)

This standalone version is backward-compatible with the bundled versions, so you
can mix and match decorators from this package with those provided by
zope.interface, TurboGears, etc.

For complete documentation, see the `DecoratorTools manual`_.

Changes since version 1.6:

* Added ``synchronized`` decorator to support locking objects during method
execution.

Changes since version 1.5:

* Added ``classy`` base class that allows you to do the most often-needed
metaclass behviors *without* needing an actual metaclass.

Changes since version 1.4:

* Added ``enclosing_frame()`` function, so that complex decorators that call
DecoratorTools functions while being called *by* DecoratorTools functions,
will work correctly.

Changes since version 1.3:

* Added support for debugging generated code, including the code generated
by ``rewrap()`` and ``template_function``.

Changes since version 1.2:

* Added ``rewrap()`` function and ``template_function`` decorator to support
signature matching for decorated functions. (These features are similar to
the ones provided by Michele Simionato's "decorator" package, but do not
require Python 2.4 and don't change the standard idioms for creating
decorator functions.)

* ``decorate_class()`` will no longer apply duplicate class decorator
callbacks unless the ``allow_duplicates`` argument is true.

Changes since version 1.1:

* Fixed a problem where instances of different struct types could equal each
other

Changes since version 1.0:

* The ``struct()`` decorator makes it easy to create tuple-like data
structure types, by decorating a constructor function.

.. _DecoratorTools Manual: http://peak.telecommunity.com/DevCenter/DecoratorTools#toc

.. _toc:

.. contents:: **Table of Contents**

You may access any of the following APIs by importing them from
``peak.util.decorators``:


Simple Decorators
-----------------

decorate(\*decorators)
Apply `decorators` to the subsequent function definition or assignment
statement, thereby allowing you to conviently use standard decorators with
Python 2.3 and up (i.e., no ``@`` syntax required), as shown in the
following table of examples::

Python 2.4+ DecoratorTools
------------ --------------
@classmethod decorate(classmethod)
def blah(cls): def blah(cls):
pass pass

@foo
@bar(baz) decorate(foo, bar(baz))
def spam(bing): def spam(bing):
"""whee""" """whee"""

decorate_class(decorator [, depth=2, frame=None])
Set up `decorator` to be passed the containing class after its creation.

This function is designed to be called by a decorator factory function
executed in a class suite. It is not used directly; instead you simply
give your users a "magic function" to call in the body of the appropriate
class. Your "magic function" (i.e. a decorator factory function) then
calls ``decorate_class`` to register the decorator to be called when the
class is created. Multiple decorators may be used within a single class,
although they must all appear *after* the ``__metaclass__`` declaration, if
there is one.

The registered decorator will be given one argument: the newly created
containing class. The return value of the decorator will be used in place
of the original class, so the decorator should return the input class if it
does not wish to replace it. Example::

>>> from peak.util.decorators import decorate_class

>>> def demo_class_decorator():
... def decorator(cls):
... print "decorating", cls
... return cls
... decorate_class(decorator)

>>> class Demo:
... demo_class_decorator()
decorating __builtin__.Demo

In the above example, ``demo_class_decorator()`` is the decorator factory
function, and its inner function ``decorator`` is what gets called to
actually decorate the class. Notice that the factory function has to be
called within the class body, even if it doesn't take any arguments.

If you are just creating simple class decorators, you don't need to worry
about the `depth` or `frame` arguments here. However, if you are creating
routines that are intended to be used within other class or method
decorators, you will need to pay attention to these arguments to ensure
that ``decorate_class()`` can find the frame where the class is being
defined. In general, the simplest way to do this is for the function
that's called in the class body to get its caller's frame with
``sys._getframe(1)``, and then pass that frame down to whatever code will
be calling ``decorate_class()``. Alternately, you can specify the `depth`
that ``decorate_class()`` should call ``sys._getframe()`` with, but this
can be a bit trickier to compute correctly.

Note, by the way that ``decorate_class()`` ignores duplicate callbacks::

>>> def hello(cls):
... print "decorating", cls
... return cls

>>> def do_hello():
... decorate_class(hello)

>>> class Demo:
... do_hello()
... do_hello()
decorating __builtin__.Demo

Unless the ``allow_duplicates`` argument is set to a true value::

>>> def do_hello():
... decorate_class(hello, allow_duplicates=True)

>>> class Demo:
... do_hello()
... do_hello()
decorating __builtin__.Demo
decorating __builtin__.Demo


The ``synchronized`` Decorator
------------------------------

When writing multithreaded programs, it's often useful to define certain
operations as being protected by a lock on an object. The ``synchronized``
decorator lets you do this by decorating object methods, e.g.::

>>> from peak.util.decorators import synchronized

>>> class TryingToBeThreadSafe(object):
... synchronized() # could be just ``@synchronized`` for 2.4+
... def method1(self, arg):
... print "in method 1"
... self.method2()
... print "back in method 1"
... return arg
...
... synchronized() # could be just ``@synchronized`` for 2.4+
... def method2(self):
... print "in method 2"
... return 42

>>> TryingToBeThreadSafe().method1(99)
in method 1
in method 2
back in method 1
99

What you can't tell from this example is that a ``__lock__`` attribute is being
acquired and released around each of those calls. Let's take a closer look::

>>> class DemoLock:
... def __init__(self, name):
... self.name = name
... def acquire(self):
... print "acquiring", self.name
... def release(self):
... print "releasing", self.name

>>> ts = TryingToBeThreadSafe()
>>> ts.__lock__ = DemoLock("lock 1")

>>> ts.method2()
acquiring lock 1
in method 2
releasing lock 1
42

>>> ts.method1(27)
acquiring lock 1
in method 1
acquiring lock 1
in method 2
releasing lock 1
back in method 1
releasing lock 1
27

As you can see, if an object already has a ``__lock__`` attribute, its
``acquire()`` and ``release()`` methods are called around the execution of the
wrapped method. (Note that this means the lock must be re-entrant: that is,
you must use a ``threading.RLock`` or something similar to it, if you
explicitly create your own ``__lock__`` attribute.)

If the object has no ``__lock__``, the decorator creates a ``threading.RLock``
and tries to add it to the object's ``__dict__``::

>>> del ts.__lock__

>>> ts.method1(27)
in method 1
in method 2
back in method 1
27

>>> ts.__lock__
<_RLock(None, 0)>

(This means, by the way, that if you want to use synchronized methods on an
object with no ``__dict__``, you must explicitly include a ``__lock__`` slot
and initialize it yourself when the object is created.)


The ``struct()`` Decorator
--------------------------

The ``struct()`` decorator creates a tuple subclass with the same name and
docstring as the decorated function. The class will have read-only properties
with the same names as the function's arguments, and the ``repr()`` of its
instances will look like a call to the original function::

>>> from peak.util.decorators import struct

>>> def X(a,b,c):
... """Demo type"""
... return a,b,c

>>> X = struct()(X) # can't use decorators above functions in doctests

>>> v = X(1,2,3)
>>> v
X(1, 2, 3)
>>> v.a
1
>>> v.b
2
>>> v.c
3

>>> help(X) # doctest: +NORMALIZE_WHITESPACE
Help on class X:
<BLANKLINE>
class X(__builtin__.tuple)
| Demo type
|
| Method resolution order:
| X
| __builtin__.tuple
| __builtin__.object
|
| Methods defined here:
|
| __repr__(self)
|
| ----------------------------------------------------------------------
| Static methods defined here:
|
| __new__(cls, *args, **kw)
|
| ----------------------------------------------------------------------
| ...s defined here:
|
| a...
|
| b...
|
| c...
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __args__ = ['a', 'b', 'c']...
|
| __star__ = None
|
| ...

The function should return a tuple of values in the same order as its argument
names, as it will be used by the class' constructor. The function can perform
validation, add defaults, and/or do type conversions on the values.

If the function takes a ``*``, argument, it should flatten this argument
into the result tuple, e.g.::

>>> def pair(first, *rest):
... return (first,) + rest
>>> pair = struct()(pair)

>>> p = pair(1,2,3,4)
>>> p
pair(1, 2, 3, 4)
>>> p.first
1
>>> p.rest
(2, 3, 4)

Internally, ``struct`` types are actually tuples::

>>> print tuple.__repr__(X(1,2,3))
(<class 'X'>, 1, 2, 3)

The internal representation contains the struct's type object, so that structs
of different types will not compare equal to each other::

>>> def Y(a,b,c):
... return a,b,c
>>> Y = struct()(Y)

>>> X(1,2,3) == X(1,2,3)
True
>>> Y(1,2,3) == Y(1,2,3)
True
>>> X(1,2,3) == Y(1,2,3)
False

Note, however, that this means that if you want to unpack them or otherwise
access members directly, you must include the type entry, or use a slice::

>>> a, b, c = X(1,2,3) # wrong
Traceback (most recent call last):
...
ValueError: too many values to unpack

>>> t, a, b, c = X(1,2,3) # right
>>> a, b, c = X(1,2,3)[1:] # ok, if perhaps a bit unintuitive

The ``struct()`` decorator takes optional mixin classes (as positional
arguments), and dictionary entries (as keyword arguments). The mixin
classes will be placed before ``tuple`` in the resulting class' bases, and
the dictionary entries will be placed in the class' dictionary. These
entries take precedence over any default entries (e.g. methods, properties,
docstring, etc.) that are created by the ``struct()`` decorator::

>>> class Mixin(object):
... __slots__ = []
... def foo(self): print "bar"

>>> def demo(a, b):
... return a, b

>>> demo = struct(Mixin, reversed=property(lambda self: self[:0:-1]))(demo)
>>> demo(1,2).foo()
bar
>>> demo(3,4).reversed
(4, 3)
>>> demo.__mro__
(<class 'demo'>, <class ...Mixin...>, <type 'tuple'>, <type 'object'>)

Note that using mixin classes will result in your new class' instances having
a ``__dict__`` attribute, unless they are new-style classes that set
``__slots__`` to an empty list. And if they have any slots other than
``__weakref__`` or ``__dict__``, this will cause a type error due to layout
conflicts. In general, it's best to use mixins only for adding methods, not
data.

Finally, note that if your function returns a non-tuple result, it will be
returned from the class' constructor. This is sometimes useful::

>>> def And(a, b):
... if a is None: return b
... return a, b
>>> And = struct()(And)

>>> And(1,2)
And(1, 2)

>>> And(None, 27)
27


Signature Matching
------------------

One of the drawbacks to using function decorators is that using ``help()`` or
other documentation tools on a decorated function usually produces unhelpful
results::

>>> def before_and_after(message):
... def decorator(func):
... def decorated(*args, **kw):
... print "before", message
... try:
... return func(*args, **kw)
... finally:
... print "after", message
... return decorated
... return decorator

>>> def foo(bar, baz):
... """Here's some doc"""

>>> foo(1,2)
>>> help(foo) # doctest: -NORMALIZE_WHITESPACE
Help on function foo:
...
foo(bar, baz)
Here's some doc
...

>>> decorated_foo = before_and_after("hello")(foo)
>>> decorated_foo(1,2)
before hello
after hello

>>> help(decorated_foo) # doctest: -NORMALIZE_WHITESPACE
Help on function decorated:
...
decorated(*args, **kw)
...

So DecoratorTools provides you with two tools to improve this situation.
First, the ``rewrap()`` function provides a simple way to match the signature,
module, and other characteristics of the original function::

>>> from peak.util.decorators import rewrap

>>> def before_and_after(message):
... def decorator(func):
... def before_and_after(*args, **kw):
... print "before", message
... try:
... return func(*args, **kw)
... finally:
... print "after", message
... return rewrap(func, before_and_after)
... return decorator

>>> decorated_foo = before_and_after("hello")(foo)
>>> decorated_foo(1,2)
before hello
after hello

>>> help(decorated_foo) # doctest: -NORMALIZE_WHITESPACE
Help on function foo:
...
foo(bar, baz)
Here's some doc
...

The ``rewrap()`` function returns you a new function object with the same
attributes (including ``__doc__``, ``__dict__``, ``__name__``, ``__module__``,
etc.) as the original function, but which calls the decorated function.

If you want the same signature but don't want the overhead of another calling
level at runtime, you can use the ``@template_function`` decorator instead.
The downside to this approach, however, is that it is more complex to use. So,
this approach is only recommended for more performance-intensive decorators,
that you've already debugged using the ``rewrap()`` approach. But if you need
to use it, the appropriate usage looks something like this::

>>> from peak.util.decorators import template_function

>>> def before_and_after2(message):
... def decorator(func):
... [template_function()] # could also be @template_function in 2.4
... def before_and_after2(__func, __message):
... '''
... print "before", __message
... try:
... return __func($args)
... finally:
... print "after", __message
... '''
... return before_and_after2(func, message)
... return decorator

>>> decorated_foo = before_and_after2("hello")(foo)
>>> decorated_foo(1,2)
before hello
after hello

>>> help(decorated_foo) # doctest: -NORMALIZE_WHITESPACE
Help on function foo:
...
foo(bar, baz)
Here's some doc
...

As you can see, the process is somewhat more complex. Any values you wish
the generated function to be able to access (aside from builtins) must be
declared as arguments to the decorating function, and all arguments must be
named so as not to conflict with the names of any of the decorated function's
arguments. The docstring must either fit on one line, or begin with a newline
and have its contents indented by at least two spaces. The string ``$args``
may be used one or more times in the docstring, whenever calling the original
function. The first argument of the decorating function must always be the
original function.


Debugging Generated Code
------------------------

Both ``rewrap()`` and ``template_function`` are implemented using code
generation and runtime compile/exec operations. Normally, such things are
frowned on in Python because Python's debugging tools don't work on generated
code. In particular, tracebacks and pdb don't show the source code of
functions compiled from strings... or do they? Let's see::

>>> def raiser(x, y="blah"):
... raise TypeError(y)

>>> def call_and_print_error(func, *args, **kw):
... # This function is necessary because we want to test the error
... # output, but doctest ignores a lot of exception detail, and
... # won't show the non-errror output unless we do it this way
... #
... try:
... func(*args, **kw)
... except:
... import sys, traceback
... print ''.join(traceback.format_exception(*sys.exc_info()))

>>> call_and_print_error(before_and_after("error")(raiser), 99)
before error
after error
Traceback (most recent call last):
File "<doctest README.txt[...]>", line ..., in call_and_print_error
func(*args, **kw)
File "<peak.util.decorators.rewrap wrapping raiser at 0x...>", line 3, in raiser
def raiser(x, y): return __decorated(x, y)
File ..., line ..., in before_and_after
return func(*args, **kw)
File "<doctest README.txt[...]>", line 2, in raiser
raise TypeError(y)
TypeError: blah

>>> call_and_print_error(before_and_after2("error")(raiser), 99)
before error
after error
Traceback (most recent call last):
File "<doctest README.txt[...]>", line ..., in call_and_print_error
func(*args, **kw)
File "<before_and_after2 wrapping raiser at 0x...>", line 6, in raiser
return __func(x, y)
File "<doctest README.txt[...]>", line 2, in raiser
raise TypeError(y)
TypeError: blah

As you can see, both decorators' tracebacks include lines from the pseudo-files
"<peak.util.decorators.rewrap wrapping raiser at 0x...>" and "<before_and_after2
wrapping raiser at 0x...>" (the hex id's of the corresponding objects are
omitted here). This is because DecoratorTools adds information to the Python
``linecache`` module, and tracebacks and pdb both use the ``linecache`` module
to get source lines. Any tools that use ``linecache``, either directly or
indirectly, will therefore be able to display this information for generated
code.

If you'd like to be able to use this feature for your own code generation or
non-file-based code (e.g. Python source loaded from a database, etc.), you can
use the ``cache_source()`` function::

>>> from peak.util.decorators import cache_source
>>> from linecache import getline

>>> demo_source = "line 1\nline 2\nline 3"

>>> cache_source("<dummy filename 1>", demo_source)
>>> getline("<dummy filename 1>", 3)
'line 3'

The function requires a dummy filename, which must be globally unique. An easy
way to ensure uniqueness is to include the ``id()`` of an object that will
exist at least as long as the source code being cached.

Also, if you have such an object, and it is weak-referenceable, you can supply
it as a third argument to ``cache_source()``, and when that object is garbage
collected the source will be removed from the ``linecache`` cache. If you're
generating a function from the source, the function object itself is ideal for
this purpose (and it's what ``rewrap()`` and ``template_function`` do)::

>>> def a_function(): pass # just an object to "own" the source

>>> cache_source("<dummy filename 2>", demo_source, a_function)
>>> getline("<dummy filename 2>", 1)
'line 1\n'

>>> del a_function # GC should now clean up the cache

>>> getline("<dummy filename 2>", 1)
''


Advanced Decorators
-------------------

The ``decorate_assignment()`` function can be used to create standalone "magic"
decorators that work in Python 2.3 and up, and which can also be used to
decorate arbitrary assignments as well as function/method definitions. For
example, if you wanted to create an ``info(**kwargs)`` decorator that could be
used either with or without an ``@``, you could do something like::

from peak.util.decorators import decorate_assignment

def info(**kw):
def callback(frame, name, func, old_locals):
func.__dict__.update(kw)
return func
return decorate_assignment(callback)

info(foo="bar") # will set dummy.foo="bar"; @info() would also work
def dummy(blah):
pass

As you can see, this ``info()`` decorator can be used without an ``@`` sign
for backward compatibility with Python 2.3. It can also be used *with* an
``@`` sign, for forward compatibility with Python 2.4 and up.

Here's a more detailed reference for the ``decorate_assignment()`` API:

decorate_assignment(callback [, depth=2, frame=None])
Call `callback(frame, name, value, old_locals)` on next assign in `frame`.

If a `frame` isn't supplied, a frame is obtained using
``sys._getframe(depth)``. `depth` defaults to 2 so that the correct frame
is found when ``decorate_assignment()`` is called from a decorator factory
that was called in the target usage context.

When `callback` is invoked, `old_locals` contains the frame's local
variables as they were *before* the assignment, thus allowing the callback
to access the previous value of the assigned variable, if any.

The callback's return value will become the new value of the variable.
`name` will contain the name of the variable being created or modified,
and `value` will be the thing being decorated. `frame` is the Python frame
in which the assignment occurred.

This function also returns a decorator function for forward-compatibility
with Python 2.4 ``@`` syntax. Note, however, that if the returned decorator
is used with Python 2.4 ``@`` syntax, the callback `name` argument may be
``None`` or incorrect, if the `value` is not the original function (e.g.
when multiple decorators are used).


"Meta-less" Classes
-------------------

Sometimes, you want to create a base class in a library or program that will
use the data defined in subclasses in some way, or that needs to customize
the way instances are created (*without* overriding ``__new__``).

Since Python 2.2, the standard way to accomplish these things is by creating
a custom metaclass and overriding ``__new__``, ``__init__``, or ``__call__``.

Unfortunately, however, metaclasses don't play well with others. If two
frameworks define independent metaclasses, and a library or application mixes
classes from those frameworks, the user will have to create a *third* metaclass
to sort out the differences. For this reason, it's best to minimize the number
of distinct metaclasses in use.

``peak.util.decorators`` therefore provides a kind of "one-size-fits-all"
metaclass, so that most of the common use cases for metaclasses can be handled
with just one metaclass. In PEAK and elsewhere, metaclasses are most commonly
used to perform some sort of operations during class creation (metaclass
``__new__`` and ``__init__``), or instance creation (metaclass ``__call__``,
wrapping the class-level ``__new__`` and ``__init__``).

Therefore, the ``classy`` base class allows subclasses to implement one or more
of the three classmethods ``__class_new__``, ``__class_init__``, and
``__class_call__``. The "one-size-fits-all" metaclass delegates these
operations to the class, so that you don't need a custom metaclass for every
class with these behaviors.

Thus, as long as all your custom metaclasses derive from ``classy.__class__``,
you can avoid any metaclass conflicts during multiple inheritance.

Here's an example of ``classy`` in use::

>>> from peak.util.decorators import classy, decorate

>>> class Demo(classy):
... """Look, ma! No metaclass!"""
...
... def __class_new__(meta, name, bases, cdict, supr):
... cls = supr()(meta, name, bases, cdict, supr)
... print "My metaclass is", meta
... print "And I am", cls
... return cls
...
... def __class_init__(cls, name, bases, cdict, supr):
... supr()(cls, name, bases, cdict, supr)
... print "Initializing", cls
...
... decorate(classmethod) # could be just @classmethod for 2.4+
... def __class_call__(cls, *args, **kw):
... print "before creating instance"
... ob = super(Demo, cls).__class_call__(*args, **kw)
... print "after creating instance"
... return ob
...
... def __new__(cls, *args, **kw):
... print "new called with", args, kw
... return super(Demo, cls).__new__(cls, *args, **kw)
...
... def __init__(self, *args, **kw):
... print "init called with", args, kw
My metaclass is <class 'peak.util.decorators.classy_class'>
And I am <class 'Demo'>
Initializing <class 'Demo'>

>>> d = Demo(1,2,a="b")
before creating instance
new called with (1, 2) {'a': 'b'}
init called with (1, 2) {'a': 'b'}
after creating instance

Note that because ``__class_new__`` and ``__class_init__`` are called *before*
the name ``Demo`` has been bound to the class under creation, ``super()``
cannot be used in these methods. So, they use a special calling convention,
where the last argument (``supr``) is the ``next()`` method of an iterator
that yields base class methods in mro order. In other words, calling
``supr()(..., supr)`` invokes the previous definition of the method. You MUST
call this exactly *once* in your methods -- no more, no less.

``__class_call__`` is different, because it is called after the class already
exists. Thus, it can be a normal ``classmethod`` and use ``super()`` in the
standard way.

Finally, note that any given ``classy`` subclass does NOT need to define all
three methods; you can mix and match methods as needed. Just be sure to always
use the ``supr`` argument (or ``super()`` in the case of ``__class_call__``).


Utility/Introspection Functions
-------------------------------

``peak.util.decorators`` also exposes these additional utility and
introspection functions that it uses internally:

frameinfo(frame)
Return a ``(kind, module, locals, globals)`` tuple for a frame

The `kind` returned is a string, with one of the following values:

* ``"exec"``
* ``"module"``
* ``"class"``
* ``"function call"``
* ``"unknown"``

The `module` returned is the Python module object whose globals are in
effect for the frame, or ``None`` if the globals don't include a value for
``__name__``.

metaclass_is_decorator(mc)
Return truth if the given metaclass is a class decorator metaclass inserted
into a class by ``decorate_class()``, or by another class decorator
implementation that follows the same protocol (such as the one in
``zope.interface``).

metaclass_for_bases(bases, explicit_mc=None)
Given a sequence of 1 or more base classes and an optional explicit
``__metaclass__``, return the metaclass that should be used. This
routine basically emulates what Python does to determine the metaclass
when creating a class, except that it does *not* take a module-level
``__metaclass__`` into account, only the arguments as given. If there
are no base classes, you should just directly use the module-level
``__metaclass__`` or ``types.ClassType`` if there is none.

enclosing_frame(frame=None, level=3)
Given a frame and/or stack level, skip upward past any DecoratorTools code
frames. This function is used by ``decorate_class()`` and
``decorate_assignment()`` to ensure that any decorators calling them that
were themselves invoked using ``decorate()``, won't end up looking at
DecoratorTools code instead of the target. If you have a function that
needs to be callable via ``decorate()`` and which inspects stack frames,
you may need to use this function to access the right frame.


Mailing List
------------

Please direct questions regarding this package to the PEAK mailing list; see
http://www.eby-sarna.com/mailman/listinfo/PEAK/ for details.
python-module-decoratortools-1.7/ez_setup.py000064400000000000000000000227641116633211000214410ustar00rootroot00000000000000#!python
"""Bootstrap setuptools installation

If you want to use setuptools in your package's setup.py, just include this
file in the same directory with it, and add this to the top of your setup.py::

from ez_setup import use_setuptools
use_setuptools()

If you want to require a specific version of setuptools, set a download
mirror, or use an alternate download directory, you can do so by supplying
the appropriate options to ``use_setuptools()``.

This file can also be run as a script to install or upgrade setuptools.
"""
import sys
DEFAULT_VERSION = "0.6c9"
DEFAULT_URL = "http://pypi.python.org/packages/%s/s/setuptools/" % sys.version[:3]

md5_data = {
'setuptools-0.6b1-py2.3.egg': '8822caf901250d848b996b7f25c6e6ca',
'setuptools-0.6b1-py2.4.egg': 'b79a8a403e4502fbb85ee3f1941735cb',
'setuptools-0.6b2-py2.3.egg': '5657759d8a6d8fc44070a9d07272d99b',
'setuptools-0.6b2-py2.4.egg': '4996a8d169d2be661fa32a6e52e4f82a',
'setuptools-0.6b3-py2.3.egg': 'bb31c0fc7399a63579975cad9f5a0618',
'setuptools-0.6b3-py2.4.egg': '38a8c6b3d6ecd22247f179f7da669fac',
'setuptools-0.6b4-py2.3.egg': '62045a24ed4e1ebc77fe039aa4e6f7e5',
'setuptools-0.6b4-py2.4.egg': '4cb2a185d228dacffb2d17f103b3b1c4',
'setuptools-0.6c1-py2.3.egg': 'b3f2b5539d65cb7f74ad79127f1a908c',
'setuptools-0.6c1-py2.4.egg': 'b45adeda0667d2d2ffe14009364f2a4b',
'setuptools-0.6c2-py2.3.egg': 'f0064bf6aa2b7d0f3ba0b43f20817c27',
'setuptools-0.6c2-py2.4.egg': '616192eec35f47e8ea16cd6a122b7277',
'setuptools-0.6c3-py2.3.egg': 'f181fa125dfe85a259c9cd6f1d7b78fa',
'setuptools-0.6c3-py2.4.egg': 'e0ed74682c998bfb73bf803a50e7b71e',
'setuptools-0.6c3-py2.5.egg': 'abef16fdd61955514841c7c6bd98965e',
'setuptools-0.6c4-py2.3.egg': 'b0b9131acab32022bfac7f44c5d7971f',
'setuptools-0.6c4-py2.4.egg': '2a1f9656d4fbf3c97bf946c0a124e6e2',
'setuptools-0.6c4-py2.5.egg': '8f5a052e32cdb9c72bcf4b5526f28afc',
'setuptools-0.6c5-py2.3.egg': 'ee9fd80965da04f2f3e6b3576e9d8167',
'setuptools-0.6c5-py2.4.egg': 'afe2adf1c01701ee841761f5bcd8aa64',
'setuptools-0.6c5-py2.5.egg': 'a8d3f61494ccaa8714dfed37bccd3d5d',
'setuptools-0.6c6-py2.3.egg': '35686b78116a668847237b69d549ec20',
'setuptools-0.6c6-py2.4.egg': '3c56af57be3225019260a644430065ab',
'setuptools-0.6c6-py2.5.egg': 'b2f8a7520709a5b34f80946de5f02f53',
'setuptools-0.6c7-py2.3.egg': '209fdf9adc3a615e5115b725658e13e2',
'setuptools-0.6c7-py2.4.egg': '5a8f954807d46a0fb67cf1f26c55a82e',
'setuptools-0.6c7-py2.5.egg': '45d2ad28f9750e7434111fde831e8372',
'setuptools-0.6c8-py2.3.egg': '50759d29b349db8cfd807ba8303f1902',
'setuptools-0.6c8-py2.4.egg': 'cba38d74f7d483c06e9daa6070cce6de',
'setuptools-0.6c8-py2.5.egg': '1721747ee329dc150590a58b3e1ac95b',
'setuptools-0.6c9-py2.3.egg': 'a83c4020414807b496e4cfbe08507c03',
'setuptools-0.6c9-py2.4.egg': '260a2be2e5388d66bdaee06abec6342a',
'setuptools-0.6c9-py2.5.egg': 'fe67c3e5a17b12c0e7c541b7ea43a8e6',
'setuptools-0.6c9-py2.6.egg': 'ca37b1ff16fa2ede6e19383e7b59245a',
}

import sys, os
try: from hashlib import md5
except ImportError: from md5 import md5

def _validate_md5(egg_name, data):
if egg_name in md5_data:
digest = md5(data).hexdigest()
if digest != md5_data[egg_name]:
print >>sys.stderr, (
"md5 validation of %s failed! (Possible download problem?)"
% egg_name
)
sys.exit(2)
return data

def use_setuptools(
version=DEFAULT_VERSION, download_base=DEFAULT_URL, to_dir=os.curdir,
download_delay=15
):
"""Automatically find/download setuptools and make it available on sys.path

`version` should be a valid setuptools version number that is available
as an egg for download under the `download_base` URL (which should end with
a '/'). `to_dir` is the directory where setuptools will be downloaded, if
it is not already available. If `download_delay` is specified, it should
be the number of seconds that will be paused before initiating a download,
should one be required. If an older version of setuptools is installed,
this routine will print a message to ``sys.stderr`` and raise SystemExit in
an attempt to abort the calling script.
"""
was_imported = 'pkg_resources' in sys.modules or 'setuptools' in sys.modules
def do_download():
egg = download_setuptools(version, download_base, to_dir, download_delay)
sys.path.insert(0, egg)
import setuptools; setuptools.bootstrap_install_from = egg
try:
import pkg_resources
except ImportError:
return do_download()
try:
pkg_resources.require("setuptools>="+version); return
except pkg_resources.VersionConflict, e:
if was_imported:
print >>sys.stderr, (
"The required version of setuptools (>=%s) is not available, and\n"
"can't be installed while this script is running. Please install\n"
" a more recent version first, using 'easy_install -U setuptools'."
"\n\n(Currently using %r)"
) % (version, e.args[0])
sys.exit(2)
else:
del pkg_resources, sys.modules['pkg_resources'] # reload ok
return do_download()
except pkg_resources.DistributionNotFound:
return do_download()

def download_setuptools(
version=DEFAULT_VERSION, download_base=DEFAULT_URL, to_dir=os.curdir,
delay = 15
):
"""Download setuptools from a specified location and return its filename

`version` should be a valid setuptools version number that is available
as an egg for download under the `download_base` URL (which should end
with a '/'). `to_dir` is the directory where the egg will be downloaded.
`delay` is the number of seconds to pause before an actual download attempt.
"""
import urllib2, shutil
egg_name = "setuptools-%s-py%s.egg" % (version,sys.version[:3])
url = download_base + egg_name
saveto = os.path.join(to_dir, egg_name)
src = dst = None
if not os.path.exists(saveto): # Avoid repeated downloads
try:
from distutils import log
if delay:
log.warn("""
---------------------------------------------------------------------------
This script requires setuptools version %s to run (even to display
help). I will attempt to download it for you (from
%s), but
you may need to enable firewall access for this script first.
I will start the download in %d seconds.

(Note: if this machine does not have network access, please obtain the file

%s

and place it in this directory before rerunning this script.)
---------------------------------------------------------------------------""",
version, download_base, delay, url
); from time import sleep; sleep(delay)
log.warn("Downloading %s", url)
src = urllib2.urlopen(url)
# Read/write all in one block, so we don't create a corrupt file
# if the download is interrupted.
data = _validate_md5(egg_name, src.read())
dst = open(saveto,"wb"); dst.write(data)
finally:
if src: src.close()
if dst: dst.close()
return os.path.realpath(saveto)




































def main(argv, version=DEFAULT_VERSION):
"""Install or upgrade setuptools and EasyInstall"""
try:
import setuptools
except ImportError:
egg = None
try:
egg = download_setuptools(version, delay=0)
sys.path.insert(0,egg)
from setuptools.command.easy_install import main
return main(list(argv)+[egg]) # we're done here
finally:
if egg and os.path.exists(egg):
os.unlink(egg)
else:
if setuptools.__version__ == '0.0.1':
print >>sys.stderr, (
"You have an obsolete version of setuptools installed. Please\n"
"remove it from your system entirely before rerunning this script."
)
sys.exit(2)

req = "setuptools>="+version
import pkg_resources
try:
pkg_resources.require(req)
except pkg_resources.VersionConflict:
try:
from setuptools.command.easy_install import main
except ImportError:
from easy_install import main
main(list(argv)+[download_setuptools(delay=0)])
sys.exit(0) # try to force an exit
else:
if argv:
from setuptools.command.easy_install import main
main(argv)
else:
print "Setuptools version",version,"or greater has been installed."
print '(Run "ez_setup.py -U setuptools" to reinstall or upgrade.)'

def update_md5(filenames):
"""Update our built-in md5 registry"""

import re

for name in filenames:
base = os.path.basename(name)
f = open(name,'rb')
md5_data[base] = md5(f.read()).hexdigest()
f.close()

data = [" %r: %r,\n" % it for it in md5_data.items()]
data.sort()
repl = "".join(data)

import inspect
srcfile = inspect.getsourcefile(sys.modules[__name__])
f = open(srcfile, 'rb'); src = f.read(); f.close()

match = re.search("\nmd5_data = {\n([^}]+)}", src)
if not match:
print >>sys.stderr, "Internal error!"
sys.exit(2)

src = src[:match.start(1)] + repl + src[match.end(1):]
f = open(srcfile,'w')
f.write(src)
f.close()


if __name__=='__main__':
if len(sys.argv)>2 and sys.argv[1]=='--md5update':
update_md5(sys.argv[2:])
else:
main(sys.argv[1:])






python-module-decoratortools-1.7/peak/000075500000000000000000000000001116633211000201365ustar00rootroot00000000000000python-module-decoratortools-1.7/peak/__init__.py000075500000000000000000000000711116633211000222500ustar00rootroot00000000000000__import__('pkg_resources').declare_namespace(__name__)

python-module-decoratortools-1.7/peak/util/000075500000000000000000000000001116633211000211135ustar00rootroot00000000000000python-module-decoratortools-1.7/peak/util/__init__.py000075500000000000000000000000701116633211000232240ustar00rootroot00000000000000__import__('pkg_resources').declare_namespace(__name__)
python-module-decoratortools-1.7/peak/util/decorators.py000064400000000000000000000503511116633211000236360ustar00rootroot00000000000000from types import ClassType, FunctionType
import sys, os
__all__ = [
'decorate_class', 'metaclass_is_decorator', 'metaclass_for_bases',
'frameinfo', 'decorate_assignment', 'decorate', 'struct', 'classy',
'template_function', 'rewrap', 'cache_source', 'enclosing_frame',
'synchronized',
]

def decorate(*decorators):
"""Use Python 2.4 decorators w/Python 2.3+

Example::

class Foo(object):
decorate(classmethod)
def something(cls,etc):
\"""This is a classmethod\"""

You can pass in more than one decorator, and they are applied in the same
order that would be used for ``@`` decorators in Python 2.4.

This function can be used to write decorator-using code that will work with
both Python 2.3 and 2.4 (and up).
"""
if len(decorators)>1:
decorators = list(decorators)
decorators.reverse()

def callback(frame,k,v,old_locals):
for d in decorators:
v = d(v)
return v
return decorate_assignment(callback)

def enclosing_frame(frame=None, level=3):
"""Get an enclosing frame that skips DecoratorTools callback code"""
frame = frame or sys._getframe(level)
while frame.f_globals.get('__name__')==__name__: frame = frame.f_back
return frame

def name_and_spec(func):
from inspect import formatargspec, getargspec
funcname = func.__name__
if funcname=='<lambda>':
funcname = "anonymous"
args, varargs, kwargs, defaults = getargspec(func)
return funcname, formatargspec(args, varargs, kwargs)[1:-1]


def qname(func):
m = func.__module__
return m and m+'.'+func.__name__ or func.__name__


def apply_template(wrapper, func, *args, **kw):
funcname, argspec = name_and_spec(func)
wrapname, wrapspec = name_and_spec(wrapper)
body = wrapper.__doc__.replace('%','%%').replace('$args','%(argspec)s')
d ={}
body = """
def %(wrapname)s(%(wrapspec)s):
def %(funcname)s(%(argspec)s): """+body+"""
return %(funcname)s
"""
body %= locals()
filename = "<%s wrapping %s at 0x%08X>" % (qname(wrapper), qname(func), id(func))
exec compile(body, filename, "exec") in func.func_globals, d

f = d[wrapname](func, *args, **kw)
cache_source(filename, body, f)

f.func_defaults = func.func_defaults
f.__doc__ = func.__doc__
f.__dict__ = func.__dict__
return f






def rewrap(func, wrapper):
"""Create a wrapper with the signature of `func` and a body of `wrapper`

Example::

def before_and_after(func):
def decorated(*args, **kw):
print "before"
try:
return func(*args, **kw)
finally:
print "after"
return rewrap(func, decorated)

The above function is a normal decorator, but when users run ``help()``
or other documentation tools on the returned wrapper function, they will
see a function with the original function's name, signature, module name,
etc.

This function is similar in use to the ``@template_function`` decorator,
but rather than generating the entire decorator function in one calling
layer, it simply generates an extra layer for signature compatibility.

NOTE: the function returned from ``rewrap()`` will have the same attribute
``__dict__`` as the original function, so if you need to set any function
attributes you should do so on the function returned from ``rewrap()``
(or on the original function), and *not* on the wrapper you're passing in
to ``rewrap()``.
"""
def rewrap(__original, __decorated):
"""return __decorated($args)"""
return apply_template(rewrap, func, wrapper)









if sys.version<"2.5":
# We'll need this for monkeypatching linecache
def checkcache(filename=None):
"""Discard cache entries that are out of date.
(This is not checked upon each call!)"""
if filename is None:
filenames = linecache.cache.keys()
else:
if filename in linecache.cache:
filenames = [filename]
else:
return
for filename in filenames:
size, mtime, lines, fullname = linecache.cache[filename]
if mtime is None:
continue # no-op for files loaded via a __loader__
try:
stat = os.stat(fullname)
except os.error:
del linecache.cache[filename]
continue
if size != stat.st_size or mtime != stat.st_mtime:
del linecache.cache[filename]


def _cache_lines(filename, lines, owner=None):
if owner is None:
owner = filename
else:
from weakref import ref
owner = ref(owner, lambda r: linecache and linecache.cache.__delitem__(filename))
global linecache; import linecache
if sys.version<"2.5" and linecache.checkcache.__module__!=__name__:
linecache.checkcache = checkcache
linecache.cache[filename] = 0, None, lines, owner

def cache_source(filename, source, owner=None):
_cache_lines(filename, source.splitlines(True), owner)



def template_function(wrapper=None):
"""Decorator that uses its wrapped function's docstring as a template

Example::

def before_and_after(func):
@template_function
def wrap(__func, __message):
'''
print "before", __message
try:
return __func($args)
finally:
print "after", __message
'''
return wrap(func, "test")

The above code will return individually-generated wrapper functions whose
signature, defaults, ``__name__``, ``__module__``, and ``func_globals``
match those of the wrapped functions.

You can use define any arguments you wish in the wrapping function, as long
as the first argument is the function to be wrapped, and the arguments are
named so as not to conflict with the arguments of the function being
wrapped. (i.e., they should have relatively unique names.)

Note that the function body will *not* have access to the globals of the
calling module, as it is compiled with the globals of the *wrapped*
function! Thus, any non-builtin values that you need in the wrapper should
be passed in as arguments to the template function.
"""
if wrapper is None:
return decorate_assignment(lambda f,k,v,o: template_function(v))
return apply_template.__get__(wrapper)







def struct(*mixins, **kw):
"""Turn a function into a simple data structure class

This decorator creates a tuple subclass with the same name and docstring as
the decorated function. The class will have read-only properties with the
same names as the function's arguments, and the ``repr()`` of its instances
will look like a call to the original function. The function should return
a tuple of values in the same order as its argument names, as it will be
used by the class' constructor. The function can perform validation, add
defaults, and/or do type conversions on the values.

If the function takes a ``*``, argument, it should flatten this argument
into the result tuple, e.g.::

@struct()
def pair(first, *rest):
return (first,) + rest

The ``rest`` property of the resulting class will thus return a tuple for
the ``*rest`` arguments, and the structure's ``repr()`` will reflect the
way it was created.

The ``struct()`` decorator takes optional mixin classes (as positional
arguments), and dictionary entries (as keyword arguments). The mixin
classes will be placed before ``tuple`` in the resulting class' bases, and
the dictionary entries will be placed in the class' dictionary. These
entries take precedence over any default entries (e.g. methods, properties,
docstring, etc.) that are created by the ``struct()`` decorator.
"""
def callback(frame, name, func, old_locals):

def __new__(cls, *args, **kw):
result = func(*args, **kw)
if type(result) is tuple:
return tuple.__new__(cls, (cls,)+result)
else:
return result

def __repr__(self):
return name+tuple.__repr__(self[1:])

import inspect
args, star, dstar, defaults = inspect.getargspec(func)

d = dict(
__new__ = __new__, __repr__ = __repr__, __doc__=func.__doc__,
__module__ = func.__module__, __args__ = args, __star__ = star,
__slots__ = [],
)

for p,a in enumerate(args):
if isinstance(a,str):
d[a] = property(lambda self, p=p+1: self[p])

if star:
d[star] = property(lambda self, p=len(args)+1: self[p:])

d.update(kw)
return type(name, mixins+(tuple,), d)

return decorate_assignment(callback)





















def synchronized(func=None):
"""Create a method synchronized by first argument's ``__lock__`` attribute

If the object has no ``__lock__`` attribute at run-time, the wrapper will
attempt to add one by creating a ``threading.RLock`` and adding it to the
object's ``__dict__``. If ``threading`` isn't available, it will use a
``dummy_threading.RLock`` instead. Neither will be imported unless the
method is called on an object that doesn't have a ``__lock__``.

This decorator can be used as a standard decorator (e.g. ``@synchronized``)
or as a Python 2.3-compatible decorator by calling it with no arguments
(e.g. ``[synchronized()]``).
"""
if func is None:
return decorate_assignment(lambda f,k,v,o: synchronized(v))

def wrap(__func):
'''
try:
lock = $self.__lock__
except AttributeError:
try:
from threading import RLock
except ImportError:
from dummy_threading import RLock
lock = $self.__dict__.setdefault('__lock__',RLock())
lock.acquire()
try:
return __func($args)
finally:
lock.release()'''
from inspect import getargspec
first_arg = getargspec(func)[0][0]
wrap.__doc__ = wrap.__doc__.replace('$self', first_arg)
return apply_template(wrap, func)






def frameinfo(frame):
"""Return (kind, module, locals, globals) tuple for a frame

'kind' is one of "exec", "module", "class", "function call", or "unknown".
"""
f_locals = frame.f_locals
f_globals = frame.f_globals

sameNamespace = f_locals is f_globals
hasModule = '__module__' in f_locals
hasName = '__name__' in f_globals
sameName = hasModule and hasName
sameName = sameName and f_globals['__name__']==f_locals['__module__']
module = hasName and sys.modules.get(f_globals['__name__']) or None
namespaceIsModule = module and module.__dict__ is f_globals

if not namespaceIsModule:
# some kind of funky exec
kind = "exec"
if hasModule and not sameNamespace:
kind="class"
elif sameNamespace and not hasModule:
kind = "module"
elif sameName and not sameNamespace:
kind = "class"
elif not sameNamespace:
kind = "function call"
else:
# How can you have f_locals is f_globals, and have '__module__' set?
# This is probably module-level code, but with a '__module__' variable.
kind = "unknown"

return kind,module,f_locals,f_globals








def decorate_class(decorator, depth=2, frame=None, allow_duplicates=False):

"""Set up `decorator` to be passed the containing class upon creation

This function is designed to be called by a decorator factory function
executed in a class suite. The factory function supplies a decorator that
it wishes to have executed when the containing class is created. The
decorator will be given one argument: the newly created containing class.
The return value of the decorator will be used in place of the class, so
the decorator should return the input class if it does not wish to replace
it.

The optional `depth` argument to this function determines the number of
frames between this function and the targeted class suite. `depth`
defaults to 2, since this skips the caller's frame. Thus, if you call this
function from a function that is called directly in the class suite, the
default will be correct, otherwise you will need to determine the correct
depth value yourself. Alternately, you can pass in a `frame` argument to
explicitly indicate what frame is doing the class definition.

This function works by installing a special class factory function in
place of the ``__metaclass__`` of the containing class. Therefore, only
decorators *after* the last ``__metaclass__`` assignment in the containing
class will be executed. Thus, any classes using class decorators should
declare their ``__metaclass__`` (if any) *before* specifying any class
decorators, to ensure that all class decorators will be applied."""

frame = enclosing_frame(frame, depth+1)
kind, module, caller_locals, caller_globals = frameinfo(frame)

if kind != "class":
raise SyntaxError(
"Class decorators may only be used inside a class statement"
)
elif not allow_duplicates and has_class_decorator(decorator, None, frame):
return

previousMetaclass = caller_locals.get('__metaclass__')
defaultMetaclass = caller_globals.get('__metaclass__', ClassType)


def advise(name,bases,cdict):

if '__metaclass__' in cdict:
del cdict['__metaclass__']

if previousMetaclass is None:
if bases:
# find best metaclass or use global __metaclass__ if no bases
meta = metaclass_for_bases(bases)
else:
meta = defaultMetaclass

elif metaclass_is_decorator(previousMetaclass):
# special case: we can't compute the "true" metaclass here,
# so we need to invoke the previous metaclass and let it
# figure it out for us (and apply its own advice in the process)
meta = previousMetaclass

else:
meta = metaclass_for_bases(bases, previousMetaclass)

newClass = meta(name,bases,cdict)

# this lets the decorator replace the class completely, if it wants to
return decorator(newClass)

# introspection data only, not used by inner function
# Note: these attributes cannot be renamed or it will break compatibility
# with zope.interface and any other code that uses this decoration protocol
advise.previousMetaclass = previousMetaclass
advise.callback = decorator

# install the advisor
caller_locals['__metaclass__'] = advise


def metaclass_is_decorator(ob):
"""True if 'ob' is a class advisor function"""
return isinstance(ob,FunctionType) and hasattr(ob,'previousMetaclass')


def iter_class_decorators(depth=2, frame=None):
frame = enclosing_frame(frame, depth+1)
m = frame.f_locals.get('__metaclass__')
while metaclass_is_decorator(m):
yield getattr(m, 'callback', None)
m = m.previousMetaclass

def has_class_decorator(decorator, depth=2, frame=None):
return decorator in iter_class_decorators(0, frame or sys._getframe(depth))
































def metaclass_for_bases(bases, explicit_mc=None):
"""Determine metaclass from 1+ bases and optional explicit __metaclass__"""

meta = [getattr(b,'__class__',type(b)) for b in bases]

if explicit_mc is not None:
# The explicit metaclass needs to be verified for compatibility
# as well, and allowed to resolve the incompatible bases, if any
meta.append(explicit_mc)

if len(meta)==1:
# easy case
return meta[0]

classes = [c for c in meta if c is not ClassType]
candidates = []

for m in classes:
for n in classes:
if issubclass(n,m) and m is not n:
break
else:
# m has no subclasses in 'classes'
if m in candidates:
candidates.remove(m) # ensure that we're later in the list
candidates.append(m)

if not candidates:
# they're all "classic" classes
return ClassType

elif len(candidates)>1:
# We could auto-combine, but for now we won't...
raise TypeError("Incompatible metatypes",bases)

# Just one, return it
return candidates[0]




def decorate_assignment(callback, depth=2, frame=None):
"""Invoke 'callback(frame,name,value,old_locals)' on next assign in 'frame'

The frame monitored is determined by the 'depth' argument, which gets
passed to 'sys._getframe()'. When 'callback' is invoked, 'old_locals'
contains a copy of the frame's local variables as they were before the
assignment took place, allowing the callback to access the previous value
of the assigned variable, if any. The callback's return value will become
the new value of the variable. 'name' is the name of the variable being
created or modified, and 'value' is its value (the same as
'frame.f_locals[name]').

This function also returns a decorator function for forward-compatibility
with Python 2.4 '@' syntax. Note, however, that if the returned decorator
is used with Python 2.4 '@' syntax, the callback 'name' argument may be
'None' or incorrect, if the 'value' is not the original function (e.g.
when multiple decorators are used).
"""
frame = enclosing_frame(frame, depth+1)
oldtrace = [frame.f_trace]
old_locals = frame.f_locals.copy()

def tracer(frm,event,arg):
if event=='call':
# We don't want to trace into any calls
if oldtrace[0]:
# ...but give the previous tracer a chance to, if it wants
return oldtrace[0](frm,event,arg)
else:
return None

try:
if frm is frame and event !='exception':
# Aha, time to check for an assignment...
for k,v in frm.f_locals.items():
if k not in old_locals or old_locals[k] is not v:
break
else:
# No luck, keep tracing
return tracer

# Got it, fire the callback, then get the heck outta here...
frm.f_locals[k] = callback(frm,k,v,old_locals)

finally:
# Give the previous tracer a chance to run before we return
if oldtrace[0]:
# And allow it to replace our idea of the "previous" tracer
oldtrace[0] = oldtrace[0](frm,event,arg)

uninstall()
return oldtrace[0]

def uninstall():
# Unlink ourselves from the trace chain.
frame.f_trace = oldtrace[0]
sys.settrace(oldtrace[0])

# Install the trace function
frame.f_trace = tracer
sys.settrace(tracer)

def do_decorate(f):
# Python 2.4 '@' compatibility; call the callback
uninstall()
frame = sys._getframe(1)
return callback(
frame, getattr(f,'__name__',None), f, frame.f_locals
)

return do_decorate











def super_next(cls, attr):
for c in cls.__mro__:
if attr in c.__dict__:
yield getattr(c, attr).im_func

class classy_class(type):
"""Metaclass that delegates selected operations back to the class"""

def __new__(meta, name, bases, cdict):
cls = super(classy_class, meta).__new__(meta, name, bases, cdict)
supr = super_next(cls, '__class_new__').next
return supr()(meta, name, bases, cdict, supr)

def __init__(cls, name, bases, cdict):
supr = super_next(cls, '__class_init__').next
return supr()(cls, name, bases, cdict, supr)

def __call__(cls, *args, **kw):
return cls.__class_call__.im_func(cls, *args, **kw)


class classy(object):
"""Base class for classes that want to be their own metaclass"""
__metaclass__ = classy_class
__slots__ = ()

def __class_new__(meta, name, bases, cdict, supr):
return type.__new__(meta, name, bases, cdict)

def __class_init__(cls, name, bases, cdict, supr):
return type.__init__(cls, name, bases, cdict)

def __class_call__(cls, *args, **kw):
return type.__call__(cls, *args, **kw)
__class_call__ = classmethod(__class_call__)






python-module-decoratortools-1.7/python-module-decoratortools.spec000064400000000000000000000023421116633211000257400ustar00rootroot00000000000000%define modulename decoratortools

Name: python-module-%modulename
Version: 1.7
Release: alt2

%setup_python_module %modulename

Summary: Use class and function decorators -- even in Python 2.3
License: PSF or ZPL
Group: Development/Python

# svn://svn.eby-sarna.com/svnroot/DecoratorTools
Url: http://pypi.python.org/pypi/DecoratorTools
Packager: Vladimir V. Kamarzin <vvk@altlinux.org>
BuildArch: noarch

Source: %name-%version.tar

BuildPreReq: %py_dependencies setuptools
Requires: python-module-peak

%description
Want to use decorators, but still need to support Python 2.3? Wish you could have class decorators, decorate arbitrary assignments, or match decorated function signatures to their original functions? Want to get metaclass features without creating metaclasses? How about synchronized methods?

"DecoratorTools" gets you all of this and more.

%prep
%setup

%build
%python_build

%install
%python_install

%files
%python_sitelibdir/peak/util/decorators*
%python_sitelibdir/*.egg-info

%changelog
* Mon Apr 06 2009 Vladimir V. Kamarzin <vvk@altlinux.org> 1.7-alt2
- Avoid file conflict with python-module-peak and add dependency on it

* Sat Apr 04 2009 Vladimir V. Kamarzin <vvk@altlinux.org> 1.7-alt1
- Initial build for Sisyphus

python-module-decoratortools-1.7/setup.cfg000075500000000000000000000000601116633211000210360ustar00rootroot00000000000000[egg_info]
tag_build = dev
tag_svn_revision = 1
python-module-decoratortools-1.7/setup.py000075500000000000000000000021451116633211000207350ustar00rootroot00000000000000#!/usr/bin/env python
"""Distutils setup file"""

import ez_setup
ez_setup.use_setuptools()
from setuptools import setup

# Metadata
PACKAGE_NAME = "DecoratorTools"
PACKAGE_VERSION = "1.7"
PACKAGES = ['peak', 'peak.util']

def get_description():
# Get our long description from the documentation
f = file('README.txt')
lines = []
for line in f:
if not line.strip():
break # skip to first blank line
for line in f:
if line.startswith('.. contents::'):
break # read to table of contents
lines.append(line)
f.close()
return ''.join(lines)

setup(
name=PACKAGE_NAME,
version=PACKAGE_VERSION,
description="Class, function, and metaclass decorators -- even in Python 2.3"
" (now with source debugging for generated code)!",
long_description = get_description(),
author="Phillip J. Eby",
author_email="peak@eby-sarna.com",
license="PSF or ZPL",
url="http://cheeseshop.python.org/pypi/DecoratorTools",
test_suite = 'test_decorators',
packages = PACKAGES,
namespace_packages = PACKAGES,
)

python-module-decoratortools-1.7/test_decorators.py000064400000000000000000000112151116633211000227740ustar00rootroot00000000000000from unittest import TestCase, makeSuite, TestSuite
from peak.util.decorators import *
import sys

def ping(log, value):

"""Class decorator for testing"""

def pong(klass):
log.append((value,klass))
return [klass]

decorate_class(pong)


def additional_tests():
import doctest
return doctest.DocFileSuite(
'README.txt',
optionflags=doctest.ELLIPSIS|doctest.NORMALIZE_WHITESPACE,
)




















class DecoratorTests(TestCase):

def testAssignAdvice(self):

log = []
def track(f,k,v,d):
log.append((f,k,v))
if k in f.f_locals:
del f.f_locals[k] # simulate old-style advisor

decorate_assignment(track,frame=sys._getframe())
test_var = 1
self.assertEqual(log, [(sys._getframe(),'test_var',1)])
log = []
decorate_assignment(track,1)
test2 = 42
self.assertEqual(log, [(sys._getframe(),'test2',42)])

# Try doing double duty, redefining an existing variable...
log = []
decorate_assignment(track,1)
decorate_assignment(track,1)

test2 = 42
self.assertEqual(log, [(sys._getframe(),'test2',42)]*2)


def testAs(self):

def f(): pass

[decorate(lambda x: [x])]
f1 = f

self.assertEqual(f1, [f])

[decorate(list, lambda x: (x,))]
f1 = f
self.assertEqual(f1, [f])


def test24DecoratorMode(self):
log = []
def track(f,k,v,d):
log.append((f,k,v))
return v

def foo(x): pass

decorate_assignment(track,1)(foo)
x = 1

self.assertEqual(log, [(sys._getframe(),'foo',foo)])





























moduleLevelFrameInfo = frameinfo(sys._getframe())

class FrameInfoTest(TestCase):

classLevelFrameInfo = frameinfo(sys._getframe())

def testModuleInfo(self):
kind,module,f_locals,f_globals = moduleLevelFrameInfo
assert kind=="module"
for d in module.__dict__, f_locals, f_globals:
assert d is globals()

def testClassInfo(self):
kind,module,f_locals,f_globals = self.classLevelFrameInfo
assert kind=="class"
assert f_locals['classLevelFrameInfo'] is self.classLevelFrameInfo
for d in module.__dict__, f_globals:
assert d is globals()


def testCallInfo(self):
kind,module,f_locals,f_globals = frameinfo(sys._getframe())
assert kind=="function call"
assert f_locals is locals() # ???
for d in module.__dict__, f_globals:
assert d is globals()


def testClassExec(self):
d = {'sys':sys, 'frameinfo':frameinfo}
exec "class Foo: info=frameinfo(sys._getframe())" in d
kind,module,f_locals,f_globals = d['Foo'].info
assert kind=="class", kind








class ClassDecoratorTests(TestCase):

def testOrder(self):
log = []
class Foo:
ping(log, 1)
ping(log, 2)
ping(log, 3)

# Strip the list nesting
for i in 1,2,3:
assert isinstance(Foo,list)
Foo, = Foo

assert log == [
(1, Foo),
(2, [Foo]),
(3, [[Foo]]),
]

def testOutside(self):
try:
ping([], 1)
except SyntaxError:
pass
else:
raise AssertionError(
"Should have detected advice outside class body"
)

def testDoubleType(self):
if sys.hexversion >= 0x02030000:
return # you can't duplicate bases in 2.3
class aType(type,type):
ping([],1)
aType, = aType
assert aType.__class__ is type




def testSingleExplicitMeta(self):

class M(type): pass

class C(M):
__metaclass__ = M
ping([],1)

C, = C
assert C.__class__ is M


def testMixedMetas(self):

class M1(type): pass
class M2(type): pass

class B1: __metaclass__ = M1
class B2: __metaclass__ = M2

try:
class C(B1,B2):
ping([],1)
except TypeError:
pass
else:
raise AssertionError("Should have gotten incompatibility error")

class M3(M1,M2): pass

class C(B1,B2):
__metaclass__ = M3
ping([],1)

assert isinstance(C,list)
C, = C
assert isinstance(C,M3)




def testMetaOfClass(self):

class metameta(type):
pass

class meta(type):
__metaclass__ = metameta

assert metaclass_for_bases((meta,type))==metameta
































python-module-decoratortools-1.7/wikiup.cfg000064400000000000000000000000431116633211000212040ustar00rootroot00000000000000[PEAK]
DecoratorTools = README.txt
 
дизайн и разработка: Vladimir Lettiev aka crux © 2004-2005, Andrew Avramenko aka liks © 2007-2008
текущий майнтейнер: Michael Shigorin