Decorator help

Jason Swails jason.swails at gmail.com
Wed Mar 27 21:33:08 CET 2013


On Wed, Mar 27, 2013 at 3:49 PM, Joseph L. Casale <jcasale at activenetwerx.com
> wrote:

> I have a class which sets up some class vars, then several methods that
> are passed in data
> and do work referencing the class vars.
>
>
> I want to decorate these methods, the decorator needs access to the class
> vars, so I thought
> about making the decorator its own class and allowing it to accept args.
>
>
> I was hoping to do all the work on in_data from within the decorator,
> which requires access
> to several MyClass vars. Not clear on the syntax/usage with this approach
> here, any guidance
> would be greatly appreciated!
>

My guess is that you don't quite 'get' decorators yet (since I remember
similar types of questions when trying to learn them myself).  Decorators
execute when the class type itself is being built (e.g., when a module is
first imported at runtime).  So decorators will never take instance
variables as arguments (nor should they, since no instance can possibly
exist when they execute).  Bear in mind, a decorator should take a callable
as an argument (and any number of 'static' parameters you want to assign
it), and return another callable.

I provide an example decorator using the format the I typically adopt below
(where the decorator is a simple function, not a class):

def my_decorator(fcn):
   """ Decorator for a function """
   def new_fcn(self, *args, **kwargs):
      """ This is the new function that we will return. """
      # You can access any instance variables here
      returnval = fcn(self, *args, **kwargs)
      # Do anything else here with instance variables
      return returnval # or any other return value you want

   return new_fcn

Notice here I define a new_fcn callable function that takes self and an
arbitrary argument/keyword-argument list, and I return this function (which
does not get called) to replace the function I passed in.  You can use
instance variables inside new_fcn since new_fcn is called by instances of
MyClass.  This is a very simple type of decorator, but hopefully helps
illustrate what decorators are.  There is a particularly good thread on SO
with information about decorators here:
http://stackoverflow.com/questions/739654/understanding-python-decorators

Hope this helps,
Jason
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20130327/481e8fb9/attachment.html>


More information about the Python-list mailing list