[New-bugs-announce] [issue11604] Have type(n, b, d) check for type(b[i]) is module

Terry J. Reedy report at bugs.python.org
Sat Mar 19 03:13:57 CET 2011


New submission from Terry J. Reedy <tjreedy at udel.edu>:

People occasionally ask on python-list about the following error message when trying to create a class:

> TypeError: Error when calling the metaclass bases
> module.__init__() takes at most 2 arguments (3 given)

It is a bit cryptic. It is also accidental: if module.__init__ happened to take 3 args instead of 2, the exception would be delayed until ???

The cause is using a module as a superclass, as in

import UserDict
class MyDict(UserDict): pass

This seems to happen mostly because of duplicate (or only case-different) module/class names.
 
Suggestion: insert a specific module type check for bases in type_new() in typeobject.c. In Python:
  if basetype is module: # where 'module' is the module class
    raise TypeError('Cannot subclass module')

I see 2 possible places to put the check:

1. for all bases - after
        tmp = PyTuple_GET_ITEM(bases, i);
        tmptype = Py_TYPE(tmp);

Advantage: can add (name of) tmp to the error message.

2. Before the return call in
    if (winner != metatype) {
        if (winner->tp_new != type_new) /* Pass it to the winner */
            return winner->tp_new(winner, args, kwds);

Advantage: only add extra check when module is the winner and are about to call it as a metaclass, which raises the current error.

Any test would be CPython specific and would require checking something about the message text.

I am only suggesting a check for module because the is the only mistake I remember anyone reporting. Passing a number as a base class gives a similar message, but no one does that. And as far as I know, there is no way in general to detect whether a callable works as a metaclass except by calling it with name, bases, and dict.

----------
components: Interpreter Core
messages: 131381
nosy: terry.reedy
priority: normal
severity: normal
stage: test needed
status: open
title: Have type(n,b,d) check for type(b[i]) is module
type: feature request
versions: Python 3.3

_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue11604>
_______________________________________


More information about the New-bugs-announce mailing list