views:

673

answers:

3

How do I find out which class I am initialising a decorator in? It makes sense that I wouldn't be able to find this out as the decorator is not yet bound to the class, but is there a way of getting round this?

class A(object):
    def dec(f):
                # I am in class 'A'
     def func(cls):
      f(cls)
     return func

    @dec
    def test(self):
     pass

I need to know which class I am (indicated by the commented line).

+3  A: 

I don't think this is possible. At the very moment when you define test, the class doesn't exist yet.

When Python encounters

class A(object):

it creates a new namespace in which it runs all code that it finds in the class definition (including the definition of test() and the call to the decorator), and when it's done, it creates a new class object and puts everything into this class that was left in the namespace after the code was executed.

So when the decorator is called, it doesn't know anything yet. At this moment, test is just a function.

balpha
A: 

I don't get the question.

>>> class A(object):
    def dec(f):
        def func(cls):
            print cls
        return func

    @dec
    def test(self):
        pass

>>> a=A()
>>> a.test()
<__main__.A object at 0x00C56330>
>>>

The argument (cls) is the class, A.

S.Lott
He wants to know *before* the definition of func (for whatever reason).
balpha
Since one doesn't appear to need to know "before" the class is defined, I don't get the question.
S.Lott
A: 

As Nadia pointed out you will need to be more specific. Python does not allow this kind of things, which means that what you are trying to do is probably something wrong.

In the meantime, here is my contribution: a little story about a sailor and a frog. (use a constructor after the class initialization)

class Cruise(object):
    def arewelostyet(self):
        print 'Young sailor: I think I am lost, help me :s'

instance = Cruise()

instance.arewelostyet()

def whereami(lostfunc):
    """
    decorator
    """
    def decorated(*args, **kwargs):
        lostfunc(*args, **kwargs)
        print 'Frog: Crôak! thou art sailing in class', lostfunc.im_class.__name__

    # don't forget to write name and doc
    decorated.func_name = lostfunc.func_name
    decorated.func_doc = lostfunc.func_name

    return decorated


print '[i]A frog pops out of nowhere[/i]'

# decorate the method:
Cruise.arewelostyet = whereami(Cruise.arewelostyet)

instance.arewelostyet()
NicDumZ