subclassing a module: misleading(?) error message

Carl Banks pavlovevidence at gmail.com
Thu Jan 4 22:31:27 CET 2007


Erik Johnson wrote:
> My questions are:
>
> Why does python complain about a function here? (it's a class definition
> statement, right?)

Because you're calling the function with the wrong number of arguments.

> Is there really a function being called here?

Yes.  (Well, it's not exactly a function, but you are calling
something.)

> If so:
>     What function was called?

types.ModuleType

>     What two arguments is it expecting?

The name of the module and a docstring.

>     What three were given?

1. The name of the class
2. The tuple of bases
3. A dict containing the symbols defined inside the class statement.

You are aware, I presume, that types (be it classes or built-in types)
are callable.  For example, to create an instance of class of class X,
you would call X().  And to create a list, you can call list().  Well,
in the same way, you can call type(), with the three arguments above,
to create classes.  And that's just what the class statement does under
the covers (usually).

The following class definition:

class A(object):
    b = 1

is exactly equivalent to this explicit call to type:

A = type("A",(object,),{"b":1})

However, there are some cases where, instead of creating the class
object itself, type will instead call some other function to create it.
 One way is if you define __metaclass__ in the class namespace: then
type will call the object spec.  Another way is if there are any bases
which have a type other than type.  (Remember, bases are supposed to be
type objects.)

That's what happened to you.  type saw that type(Super) was
types.ModuleType, not type, so it called that instead of creating the
class itself.  However, types.ModuleType doesn't accept that same
arguments that a normal type constructor does, so you get the error.

Does that clear things up?  Probably not.  For a detailed explanation
of how this all works, look for some resources on learning
"metaclasses" or "metatypes" in Python.


Carl Banks




More information about the Python-list mailing list