New submission from Eric Snow:

Currently type_new() in Objects/typeobject.c enforces a restriction that the 
namespace be a dict or dict subclass.  It does this via the 
PyArg_ParseTupleAndKeywords() call there.

This means that valid mappings may not be used even though they should work 
just fine.  A demonstration of the problem is below.

I've attached a patch that relaxes this restriction.  Should we also add a note 
in the docs that type() will take anything for namespace that dict() will take?

Demonstration
-------------

class Meta(type):
    @classmethod
    def __prepare__(cls, name, bases, **kwargs):
        return ClassMapping()

from collections import MutableMapping
class ClassMapping(MutableMapping):
    def __init__(self, *args, **kwargs):
        self._dict = dict(*args, **kwargs)
    def __len__(self):
      return len(self._dict)
    def __iter__(self):
        return iter(self._dict)
    def __getitem__(self, key):
        return self._dict[key]
    def __setitem__(self, key, value):
        self._dict[key] = value
    def __delitem__(self, key):
        del self._dict[key]

>>> class X(metaclass=Meta):
...     pass
...
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: type() argument 3 must be dict, not ClassMapping

----------
files: type-namespace-restriction.diff
keywords: patch
messages: 184187
nosy: eric.snow, ncoghlan
priority: normal
severity: normal
stage: patch review
status: open
title: Drop restriction that meta.__prepare__() must return a dict (subclass)
type: enhancement
versions: Python 3.4
Added file: http://bugs.python.org/file29408/type-namespace-restriction.diff

_______________________________________
Python tracker <rep...@bugs.python.org>
<http://bugs.python.org/issue17421>
_______________________________________
_______________________________________________
Python-bugs-list mailing list
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com

Reply via email to