Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access self from decorator

In setUp() method of unittest I've setup some self variables, which are later referenced in actual tests. I've also created a decorator to do some logging. Is there a way in which I can access those self variables from decorator?

For the sake of simplicity, I'm posting this code:

def decorator(func):     def _decorator(*args, **kwargs):         # access a from TestSample         func(*args, **kwargs)     return _decorator  class TestSample(unittest.TestCase):         def setUp(self):         self.a = 10      def tearDown(self):         # tear down code      @decorator     def test_a(self):         # testing code goes here 

What would be the best way of accessing a (set in setUp()) from decorator?

like image 805
kevin Avatar asked Sep 28 '11 23:09

kevin


People also ask

Can a decorator access self?

If you want to access self (instanse where decorator is called from) you can use args[0] inside the decorator.

Can decorator return value?

Writing your own decorator Any function can be used as a decorator. In this example the decorator is passed a function, and returns a different object. It simply swallows the function it is given entirely, and always returns 5.

Why would you use a decorator?

You'll use a decorator when you need to change the behavior of a function without modifying the function itself. A few good examples are when you want to add logging, test performance, perform caching, verify permissions, and so on. You can also use one when you need to run the same code on multiple functions.


1 Answers

Since you're decorating a method, and self is a method argument, your decorator has access to self at runtime. Obviously not at parsetime, because there are no objects yet, just a class.

So you change your decorator to:

def decorator(func):     def _decorator(self, *args, **kwargs):         # access a from TestSample         print 'self is %s' % self         return func(self, *args, **kwargs)     return _decorator 
like image 172
Dave Avatar answered Sep 21 '22 22:09

Dave