1

I have next code

def timer_dec(f):
    def wrapper(*args, **kwargs):
        t = time.time()
        args[0].debug('<{}> start'.format(f.__name__))
        res = f(*args, **kwargs)
        args[0].debug('<{}> finish'.format(f.__name__))
        args[0].debug("Working time for function <%s>: %f" % (f.__name__, time.time() - t))
        return  res

    return wrapper

This is works fine:

@timer_dec
class A(object):
  pass

But this is not working:

@timer_dec
class A(object):
  pass

class B(A):
  pass

TypeError: Error when calling the metaclass bases function() argument 1 must be code, not str

Python version is 2.7

user19911303
  • 449
  • 2
  • 9
  • 34
ngelik
  • 17
  • 1
  • 4

2 Answers2

4

You seem to be using a function decorator as a class decorator.

@timer_dec
class A(object):
  pass

is equivalent to

class A(object):
  pass
A = timer_dec(A)

Because timer_dec returns a function, A is now a function.


You can create a class decorator that applies a function decorator to all methods of the class. See here for an example: Alex Martelli's answer to Applying python decorators to methods in a class

Community
  • 1
  • 1
Janne Karila
  • 24,266
  • 6
  • 53
  • 94
0

Your decorator is returning a function. Thus, after the decorator call, the name "A" is bound to a function, not a class. Then, you try to inherit B from the function A, which is illegal.

shx2
  • 61,779
  • 13
  • 130
  • 153