The Artima Developer Community
Sponsored Link

Python Answers Forum
Playing with decorators

3 replies on 1 page. Most recent reply: Aug 10, 2004 6:26 AM by Andy

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 3 replies on 1 page
Chris Dutton

Posts: 15
Nickname: cdutton
Registered: Jul, 2004

Playing with decorators Posted: Aug 8, 2004 4:00 PM
Reply to this message Reply
Advertisement
So I downloaded 2.4a2 and I'm playing with decorators. One thing I'd like to do is create a couple of decorators which execute a function before the first function executes, and one which executes something afterward.

Any tips?


Andy

Posts: 28
Nickname: adn
Registered: Jul, 2004

Re: Playing with decorators Posted: Aug 9, 2004 5:22 AM
Reply to this message Reply
I guess you'd have to put together a new function;

def before():
print "I'm about to go in!"

def after():
print "I've been in!"

def before_and_after(func):
"""
Return a function that calls before(), func() then
after() in that order.
"""

def wrapped(room_name):
""" The new function """
before()
func(room_name)
after()

return wrapped

@before_and_after
def whatRoom(room_name):
print "I'm in the %s" % room_name


>>> whatRoom('kitchen')
I'm about to go in!
I'm in the kitchen
I've been in!

Chris Dutton

Posts: 15
Nickname: cdutton
Registered: Jul, 2004

Re: Playing with decorators Posted: Aug 9, 2004 1:13 PM
Reply to this message Reply
I got that much to work. The next step up would be to enable a decorator which can take an arbitrary function and it's arguments as arguments.

@pre(some_func, 1, 2, 3)
@post(some_other_func, "foo", "bar")
def foo():
print "hello world!"

Andy

Posts: 28
Nickname: adn
Registered: Jul, 2004

Re: Playing with decorators Posted: Aug 10, 2004 6:26 AM
Reply to this message Reply
This descriptor stuff is quite a brainfeck. But ...

Use the *arg_list and **arg_dict syntax.

def pre(pre_func, *arg_list, **arg_dict):
def wrapped(func):
pre_func(*arg_list, **arg)
# Assuming your function to be decorated doesn't take
# any arguments ...
func()
return wrapped

I'll let you figure out the post function.

Look at the documentation, it should make things a bit clearer. Look at the "4 PEP 318: Decorators for Functions, Methods and Classes" under "What's New in Python".

Flat View: This topic has 3 replies on 1 page
Topic: is exec() what I want? Previous Topic   Next Topic Topic: random from an array

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use