A
A
alhimik452013-10-01 11:56:47
Python
alhimik45, 2013-10-01 11:56:47

Pass the class itself to the class method decorator

Here is a simple decorator:

def deco(clazz):
  def dec(fn):
    print clazz,fn
    return fn
  return dec

We are trying to use it:
class Foo(object):
  @deco(Foo)
  def Bar():
    print "bar"

On startup it says:
Traceback (most recent call last):
  File "<pyshell#12>", line 1, in <module>
    class Foo(object):
  File "<pyshell#12>", line 2, in Foo
    @deco(Foo)
NameError: name 'Foo' is not defined

Actually, why does he not see the class and how can this be bypassed?

Answer the question

In order to leave comments, you need to log in

4 answer(s)
A
Alexey Akulovich, 2013-10-01
@AterCattus

Because at the time of the execution of the class body, it has not yet been formed.
You can for example like this:

import traceback

def deco():
    clazz = traceback.extract_stack()[1][2]
    def dec(fn):
        print clazz,fn
        return fn
    return dec

class Foo(object):
    @deco()
    def Bar():
        print "bar"

Maybe someone will offer something better, something the head does not cook.

X
xSus, 2013-10-02
@xSus

Method level decorator - solves the issues of the method itself. And it is not correct to try to extend it to the class level. Understand that a method can be declared anywhere and assigned to any class in any other method. What should the decorator return in this case? Such a python. It is necessary to try to reformulate the problem, perhaps the solution is not in the decorators at all?

J
JustAMan, 2013-10-02
@JustAMan

It looks like what implements the answer to the question posed is this example:
wiki.python.org/moin/PythonDecoratorLibrary#CA-1f74040af898602b483f2d7691d29b4a5644cce2_1

H
homm, 2013-11-14
@homm

> I need to get the class object in the decorator and add a couple of properties to it. Metaclasses are more suitable for this. In any case, you won't get the class object at the moment the decorator of its method is called - the class hasn't been created yet.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question