我们从Python开源项目中,提取了以下45个代码示例,用于说明如何使用types.ModuleType.__new__()。
def test_newslots(self): # Testing __new__ slot override... class C(list): def __new__(cls): self = list.__new__(cls) self.foo = 1 return self def __init__(self): self.foo = self.foo + 2 a = C() self.assertEqual(a.foo, 3) self.assertEqual(a.__class__, C) class D(C): pass b = D() self.assertEqual(b.foo, 3) self.assertEqual(b.__class__, D)
def test_funny_new(self): # Testing __new__ returning something unexpected... class C(object): def __new__(cls, arg): if isinstance(arg, str): return [1, 2, 3] elif isinstance(arg, int): return object.__new__(D) else: return object.__new__(cls) class D(C): def __init__(self, arg): self.foo = arg self.assertEqual(C("1"), [1, 2, 3]) self.assertEqual(D("1"), [1, 2, 3]) d = D(None) self.assertEqual(d.foo, None) d = C(1) self.assertIsInstance(d, D) self.assertEqual(d.foo, 1) d = D(1) self.assertIsInstance(d, D) self.assertEqual(d.foo, 1)
def test_recursions_1(self): # Testing recursion checks ... class Letter(str): def __new__(cls, letter): if letter == 'EPS': return str.__new__(cls) return str.__new__(cls, letter) def __str__(self): if not self: return 'EPS' return self # sys.stdout needs to be the original to trigger the recursion bug test_stdout = sys.stdout sys.stdout = test_support.get_original_stdout() try: # nothing should actually be printed, this should raise an exception print Letter('w') except RuntimeError: pass else: self.fail("expected a RuntimeError for print recursion") finally: sys.stdout = test_stdout
def test_complexes(self): # Testing complex operations... self.number_operators(100.0j, 3.0j, skip=['lt', 'le', 'gt', 'ge', 'int', 'float', 'divmod', 'mod']) class Number(complex): __slots__ = ['prec'] def __new__(cls, *args, **kwds): result = complex.__new__(cls, *args) result.prec = kwds.get('prec', 12) return result def __repr__(self): prec = self.prec if self.imag == 0.0: return "%.*g" % (prec, self.real) if self.real == 0.0: return "%.*gj" % (prec, self.imag) return "(%.*g+%.*gj)" % (prec, self.real, prec, self.imag) __str__ = __repr__ a = Number(3.14, prec=6) self.assertEqual(repr(a), "3.14") self.assertEqual(a.prec, 6) a = Number(a, prec=2) self.assertEqual(repr(a), "3.1") self.assertEqual(a.prec, 2) a = Number(234.5) self.assertEqual(repr(a), "234.5") self.assertEqual(a.prec, 12)
def test_unintialized_modules(self): # Testing uninitialized module objects... from types import ModuleType as M m = M.__new__(M) str(m) self.assertEqual(hasattr(m, "__name__"), 0) self.assertEqual(hasattr(m, "__file__"), 0) self.assertEqual(hasattr(m, "foo"), 0) self.assertFalse(m.__dict__) # None or {} are both reasonable answers m.foo = 1 self.assertEqual(m.__dict__, {"foo": 1})
def test_complexes(self): # Testing complex operations... self.number_operators(100.0j, 3.0j, skip=['lt', 'le', 'gt', 'ge', 'int', 'long', 'float']) class Number(complex): __slots__ = ['prec'] def __new__(cls, *args, **kwds): result = complex.__new__(cls, *args) result.prec = kwds.get('prec', 12) return result def __repr__(self): prec = self.prec if self.imag == 0.0: return "%.*g" % (prec, self.real) if self.real == 0.0: return "%.*gj" % (prec, self.imag) return "(%.*g+%.*gj)" % (prec, self.real, prec, self.imag) __str__ = __repr__ a = Number(3.14, prec=6) self.assertEqual(repr(a), "3.14") self.assertEqual(a.prec, 6) a = Number(a, prec=2) self.assertEqual(repr(a), "3.1") self.assertEqual(a.prec, 2) a = Number(234.5) self.assertEqual(repr(a), "234.5") self.assertEqual(a.prec, 12)
def test_uninitialized_modules(self): # Testing uninitialized module objects... from types import ModuleType as M m = M.__new__(M) str(m) self.assertNotHasAttr(m, "__name__") self.assertNotHasAttr(m, "__file__") self.assertNotHasAttr(m, "foo") self.assertFalse(m.__dict__) # None or {} are both reasonable answers m.foo = 1 self.assertEqual(m.__dict__, {"foo": 1})
def test_unintialized_modules(self): # Testing uninitialized module objects... from types import ModuleType as M m = M.__new__(M) str(m) self.assertNotHasAttr(m, "__name__") self.assertNotHasAttr(m, "__file__") self.assertNotHasAttr(m, "foo") self.assertFalse(m.__dict__) # None or {} are both reasonable answers m.foo = 1 self.assertEqual(m.__dict__, {"foo": 1})
def test_complexes(self): # Testing complex operations... self.number_operators(100.0j, 3.0j, skip=['lt', 'le', 'gt', 'ge', 'int', 'float', 'floordiv', 'divmod', 'mod']) class Number(complex): __slots__ = ['prec'] def __new__(cls, *args, **kwds): result = complex.__new__(cls, *args) result.prec = kwds.get('prec', 12) return result def __repr__(self): prec = self.prec if self.imag == 0.0: return "%.*g" % (prec, self.real) if self.real == 0.0: return "%.*gj" % (prec, self.imag) return "(%.*g+%.*gj)" % (prec, self.real, prec, self.imag) __str__ = __repr__ a = Number(3.14, prec=6) self.assertEqual(repr(a), "3.14") self.assertEqual(a.prec, 6) a = Number(a, prec=2) self.assertEqual(repr(a), "3.1") self.assertEqual(a.prec, 2) a = Number(234.5) self.assertEqual(repr(a), "234.5") self.assertEqual(a.prec, 12)
def __new__(mcls, name, bases, attrs): if attrs.get('__doc__') is None: attrs['__doc__'] = name # helps when debugging with gdb return type.__new__(mcls, name, bases, attrs)
def test_mutable_bases_with_failing_mro(self): # Testing mutable bases with failing mro... class WorkOnce(type): def __new__(self, name, bases, ns): self.flag = 0 return super(WorkOnce, self).__new__(WorkOnce, name, bases, ns) def mro(self): if self.flag > 0: raise RuntimeError("bozo") else: self.flag += 1 return type.mro(self) class WorkAlways(type): def mro(self): # this is here to make sure that .mro()s aren't called # with an exception set (which was possible at one point). # An error message will be printed in a debug build. # What's a good way to test for this? return type.mro(self) class C(object): pass class C2(object): pass class D(C): pass class E(D): pass class F(D, metaclass=WorkOnce): pass class G(D, metaclass=WorkAlways): pass # Immediate subclasses have their mro's adjusted in alphabetical # order, so E's will get adjusted before adjusting F's fails. We # check here that E's gets restored. E_mro_before = E.__mro__ D_mro_before = D.__mro__ try: D.__bases__ = (C2,) except RuntimeError: self.assertEqual(E.__mro__, E_mro_before) self.assertEqual(D.__mro__, D_mro_before) else: self.fail("exception not propagated")
def test_altmro(self): # Testing mro() and overriding it... class A(object): def f(self): return "A" class B(A): pass class C(A): def f(self): return "C" class D(B, C): pass self.assertEqual(D.mro(), [D, B, C, A, object]) self.assertEqual(D.__mro__, (D, B, C, A, object)) self.assertEqual(D().f(), "C") class PerverseMetaType(type): def mro(cls): L = type.mro(cls) L.reverse() return L class X(D,B,C,A): __metaclass__ = PerverseMetaType self.assertEqual(X.__mro__, (object, A, C, B, D, X)) self.assertEqual(X().f(), "A") try: class X(object): class __metaclass__(type): def mro(self): return [self, dict, object] # In CPython, the class creation above already raises # TypeError, as a protection against the fact that # instances of X would segfault it. In other Python # implementations it would be ok to let the class X # be created, but instead get a clean TypeError on the # __setitem__ below. x = object.__new__(X) x[5] = 6 except TypeError: pass else: self.fail("devious mro() return not caught") try: class X(object): class __metaclass__(type): def mro(self): return [1] except TypeError: pass else: self.fail("non-class mro() return not caught") try: class X(object): class __metaclass__(type): def mro(self): return 1 except TypeError: pass else: self.fail("non-sequence mro() return not caught")
def test_mutable_bases_with_failing_mro(self): # Testing mutable bases with failing mro... class WorkOnce(type): def __new__(self, name, bases, ns): self.flag = 0 return super(WorkOnce, self).__new__(WorkOnce, name, bases, ns) def mro(self): if self.flag > 0: raise RuntimeError, "bozo" else: self.flag += 1 return type.mro(self) class WorkAlways(type): def mro(self): # this is here to make sure that .mro()s aren't called # with an exception set (which was possible at one point). # An error message will be printed in a debug build. # What's a good way to test for this? return type.mro(self) class C(object): pass class C2(object): pass class D(C): pass class E(D): pass class F(D): __metaclass__ = WorkOnce class G(D): __metaclass__ = WorkAlways # Immediate subclasses have their mro's adjusted in alphabetical # order, so E's will get adjusted before adjusting F's fails. We # check here that E's gets restored. E_mro_before = E.__mro__ D_mro_before = D.__mro__ try: D.__bases__ = (C2,) except RuntimeError: self.assertEqual(E.__mro__, E_mro_before) self.assertEqual(D.__mro__, D_mro_before) else: self.fail("exception not propagated")