On 17 kesä, 10:47, voltron <[EMAIL PROTECTED]> wrote:
> I am having problems using decorators with controllers. In a test
> controller:
[clip]
> I have to pass "self" to the function passed to the decorator somehow,
> what would be the best way to do this? I want the decorator to carry
> out a few things before calling the controller function its
> decorating.

A generic decorator factory looks like this

    def dec(whatever_parameter):
        def decorator(func):
            def wrapper(*a, **kw):
                print whatever_parameter, a, kw
                return func(*a, **kw)
            return wrapper
        return decorator

So, consider

    class Foo(object):
        @dec("calling foo")
        def foo(self):
            print "foo"

        @dec("calling bar")
        def bar(self, k, m):
            print "bar", k, m

This is *equivalent* to (and so for all decorators, the @ is just
syntax sugar)

    class Foo(object):
        def foo(self):
            print "foo"

        foo = dec("calling foo")(foo)

        def bar(self, k, m):
            print "bar", k, m

        bar = dec("calling bar")(bar)

That is, both "dec" and "decorator" are run already when the module
is imported. The "decorator" should return a function that is fit
to be used as a class method, i.e. accepts "self" as the first
parameter.

Now,

    a = Foo()
    a.foo()
    a.bar(5, m=6)

prints

    calling foo (<__main__.Foo object at 0xb7cf74ac>,) {}
    foo
    calling bar (<__main__.Foo object at 0xb7cf74ac>, 5) {'m': 6}
    bar 5 6

That is, the wrapper is run every time either foo or bar is called.
Note that 'self' is the first parameter to wrapper (the first entry in
*a),
since it is called as a class method. Keyword parameters go to the
**kw dict.

So if you want to "pass" self to the wrapper explicitly, you can write
the wrapper for example like

    def wrapper(self, *a, **kw):
        # do something with self
        return func(self, *a, **kw)

Hope this clarifies decorators a bit.

--
Pauli Virtanen


--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups 
"pylons-discuss" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/pylons-discuss?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to