tags:

views:

51

answers:

2

Just playin around class

def func(*args, **kwargs):
    print args, kwargs

class Klass(func): pass

it throws error

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

What does it mean, i am passing no str nowhere? and yes I should be passing class in bases but why didn't error say that, instead of this cryptic error?

A: 

func is not a class, so you cannot inherit it. What would that mean?

Mike Graham
but that python should tell me if it isn't allowed, instead it says something about str/code not abt class/func
Python creates classes based on the type of the base class. This is normally `type`, but for legacy old-style classes this is `classobj` and in general it can be an arbitrary callable. When you pass something that isn't enough like a class (like most instances, like `4` or `[]` or this function), Python naively tries to call its type (`int` or `list` or `function`) as though it were a metaclass. It is difficult to distinguish whether your error was from an intentional metaclass definition or because you passed an instance, but it would be better if the error message provided some more guidance
Mike Graham
Incidentally, http://bugs.python.org/issue6829 was opened in response to the quality of this error message.
Mike Graham
+1  A: 

see here for the reason for the cryptic msg

http://bugs.python.org/issue6829

questions http://stackoverflow.com/questions/2231427/error-when-calling-the-metaclass-bases-function-argument-1-must-be-code-not-s/2231478 has same problem.

Edit: play-around

Though you can use metaclass to make it work in a twisted way ;)

def func(name, klassDict):
    return type(name, (), klassDict)

class MyMeta(type):
    def __new__(self, name, bases, klassDict):
        return bases[0](name, klassDict)

class Klass(func):
    __metaclass__ = MyMeta

print Klass
Anurag Uniyal