Skip to content

Instantly share code, notes, and snippets.



Created Sep 3, 2014
What would you like to do?
type() bug?
class NS:
PASSTHRU = frozenset(('__name__', '__qualname__', '__doc__', '__module__'))
def __init__(self, data=None):
if data is None:
data = {} = data
def __setitem__(self, name, value):
if name in self.PASSTHRU:[name] = value
elif isinstance(value, str):[name] = value
raise TypeError
def __getitem__(self, name):
if name in self.PASSTHRU:
elif name in
else:[name] = name
class Meta(type):
def __prepare__(mcls, name, bases):
return NS()
def __new__(mcls, name, bases, ns):
classdict =
return type.__new__(mcls, name, bases, classdict)
class Def(metaclass=Meta):
class Example(Def):
a = 'a'
b = 'b'
c = 'c'
assert Example.a == 'a'
assert Example.b == 'b'
assert Example.c == 'c'
BrokenExample1 = type('BrokenExample1', (Def, ), NS({'x': 'x'}))
# Traceback (most recent call last):
# File "", line 53, in <module>
# BrokenExample1 = type('BrokenExample1', (Def, ), NS({'x': 'x'}))
# TypeError: type() argument 3 must be dict, not NS
BrokenExample2 = type('BrokenExample2', (Def, ), {'x': 'x'})
# Traceback (most recent call last):
# File "", line 58, in <module>
# BrokenExample2 = type('BrokenExample2', (Def, ), {'x': 'x'})
# File "", line 35, in __new__
# classdict =
# AttributeError: 'dict' object has no attribute 'data'

This comment has been minimized.

Copy link
Owner Author

@zyga zyga commented Sep 3, 2014

Yes I've figured it out... on line 52 I should have used Meta...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment