Python types.new_class() Examples

The following are code examples for showing how to use types.new_class(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: NiujiaoDebugger   Author: MrSrc   File: test_types.py    GNU General Public License v3.0 6 votes vote down vote up
def test_prepare_class(self):
        # Basic test of metaclass derivation
        expected_ns = {}
        class A(type):
            def __new__(*args, **kwargs):
                return type.__new__(*args, **kwargs)

            def __prepare__(*args):
                return expected_ns

        B = types.new_class("B", (object,))
        C = types.new_class("C", (object,), {"metaclass": A})

        # The most derived metaclass of D is A rather than type.
        meta, ns, kwds = types.prepare_class("D", (B, C), {"metaclass": type})
        self.assertIs(meta, A)
        self.assertIs(ns, expected_ns)
        self.assertEqual(len(kwds), 0) 
Example 2
Project: NiujiaoDebugger   Author: MrSrc   File: test_types.py    GNU General Public License v3.0 6 votes vote down vote up
def test_metaclass_override_function(self):
        # Special case: the given metaclass isn't a class,
        # so there is no metaclass calculation.
        class A(metaclass=self.Meta):
            pass

        marker = object()
        def func(*args, **kwargs):
            return marker

        X = types.new_class("X", (), {"metaclass": func})
        Y = types.new_class("Y", (object,), {"metaclass": func})
        Z = types.new_class("Z", (A,), {"metaclass": func})
        self.assertIs(marker, X)
        self.assertIs(marker, Y)
        self.assertIs(marker, Z) 
Example 3
Project: NiujiaoDebugger   Author: MrSrc   File: util.py    GNU General Public License v3.0 6 votes vote down vote up
def specialize_class(cls, kind, base=None, **kwargs):
    # XXX Support passing in submodule names--load (and cache) them?
    # That would clean up the test modules a bit more.
    if base is None:
        base = unittest.TestCase
    elif not isinstance(base, type):
        base = base[kind]
    name = '{}_{}'.format(kind, cls.__name__)
    bases = (cls, base)
    specialized = types.new_class(name, bases)
    specialized.__module__ = cls.__module__
    specialized._NAME = cls.__name__
    specialized._KIND = kind
    for attr, values in kwargs.items():
        value = values[kind]
        setattr(specialized, attr, value)
    return specialized 
Example 4
Project: MiniGames   Author: fyabc   File: enchantment.py    MIT License 6 votes vote down vote up
def create_enchantment(data, apply_fn, apply_imm_fn=None, base=Enchantment,
                       name=None, module_dict=None, add_to_module=False):
    assert 'id' in data, 'Data must contain value of key "id".'

    if apply_imm_fn is None:
        def apply_imm_fn(self):
            pass

    if name is None:
        if 'name' in data:
            name = data['name']
        else:
            name = '{}_{}'.format(Enchantment.__name__, data['id'])

    cls_dict = {'data': data, 'apply': apply_fn, 'apply_imm': apply_imm_fn}

    cls = _new_class(name, (base,), {}, lambda ns: ns.update(cls_dict))
    if add_to_module:
        _add_to_module(cls, module_dict)

    return cls 
Example 5
Project: MiniGames   Author: fyabc   File: utils.py    MIT License 6 votes vote down vote up
def create_card(data, name, card_type, cls_dict_others=None):
    """Internal function to create a card, called by other creators."""

    assert 'id' in data, 'Data must contain value of key "id".'

    if name is None:
        if 'name' in data:
            name = data['name']
        else:
            name = '{}_{}'.format(card_type.__name__, data['id'])

    cls_dict = {'data': data}

    if cls_dict_others is not None:
        cls_dict.update(cls_dict_others)

    return new_class(name, (card_type,), {}, lambda ns: ns.update(cls_dict)) 
Example 6
Project: edgedb   Author: edgedb   File: commondl.py    Apache License 2.0 6 votes vote down vote up
def _new_nonterm(self, clsname, clsdict=None, clskwds=None,
                     clsbases=(Nonterm,)):
        if clsdict is None:
            clsdict = {}
        if clskwds is None:
            clskwds = {}
        mod = sys.modules[self.name]

        def clsexec(ns):
            ns['__module__'] = self.name
            for k, v in clsdict.items():
                ns[k] = v
            return ns

        cls = types.new_class(clsname, clsbases, clskwds, clsexec)
        setattr(mod, clsname, cls)
        return cls 
Example 7
Project: cqp-sdk-for-py37-native   Author: crud-boy   File: test_types.py    GNU General Public License v2.0 6 votes vote down vote up
def test_prepare_class(self):
        # Basic test of metaclass derivation
        expected_ns = {}
        class A(type):
            def __new__(*args, **kwargs):
                return type.__new__(*args, **kwargs)

            def __prepare__(*args):
                return expected_ns

        B = types.new_class("B", (object,))
        C = types.new_class("C", (object,), {"metaclass": A})

        # The most derived metaclass of D is A rather than type.
        meta, ns, kwds = types.prepare_class("D", (B, C), {"metaclass": type})
        self.assertIs(meta, A)
        self.assertIs(ns, expected_ns)
        self.assertEqual(len(kwds), 0) 
Example 8
Project: cqp-sdk-for-py37-native   Author: crud-boy   File: test_types.py    GNU General Public License v2.0 6 votes vote down vote up
def test_metaclass_override_function(self):
        # Special case: the given metaclass isn't a class,
        # so there is no metaclass calculation.
        class A(metaclass=self.Meta):
            pass

        marker = object()
        def func(*args, **kwargs):
            return marker

        X = types.new_class("X", (), {"metaclass": func})
        Y = types.new_class("Y", (object,), {"metaclass": func})
        Z = types.new_class("Z", (A,), {"metaclass": func})
        self.assertIs(marker, X)
        self.assertIs(marker, Y)
        self.assertIs(marker, Z) 
Example 9
Project: pymtl3   Author: cornell-brg   File: bitstructs.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def mk_bitstruct( cls_name, fields, *, namespace=None, add_init=True,
                   add_str=True, add_repr=True, add_hash=True ):

  # copy namespace since  will mutate it
  namespace = {} if namespace is None else namespace.copy()

  # We assume fields is a dictionary and thus there won't be duplicate
  # field names. So we only check if the field names are indeed strings
  # and that they are not keywords.
  annos = {}
  for name, f in fields.items():
    if not isinstance( name, str ) or not name.isidentifier():
      raise TypeError( f'Field name {name!r} is not a valid identifier!' )
    if keyword.iskeyword( name ):
      raise TypeError( f'Field name {name!r} is a keyword!' )
    annos[ name ] = f

  namespace['__annotations__'] = annos
  cls = types.new_class( cls_name, (), {}, lambda ns: ns.update( namespace ) )
  return bitstruct( cls, add_init=add_init, add_str=add_str,
                    add_repr=add_repr, add_hash=add_hash ) 
Example 10
Project: onto2nx   Author: cthoyt   File: nx2onto.py    GNU General Public License v3.0 6 votes vote down vote up
def nx_to_ontology(graph, source_node, output_path, base_iri):
    """Graph nodes are ID's, and have a 'label' in the node data with the right label

    :param graph:
    :param source_node:
    :param str output_path:
    :param base_iri:
    """
    ontology = owlready.Ontology(base_iri)

    parent_lookup = {
        source_node: types.new_class(source_node, (owlready.Thing,), kwds={"ontology": ontology})
    }

    def recur(pnode):
        for neighbor in graph.neighbors(pnode):
            data = graph.node[neighbor]
            neighbor_class = types.new_class(neighbor, (parent_lookup[pnode],), kwds={"ontology": ontology})
            owlready.ANNOTATIONS[neighbor_class].add_annotation(owlready.rdfs.label, data['label'])
            recur(neighbor)

    recur(source_node)

    ontology.save(filename=output_path) 
Example 11
Project: simpledet   Author: TuSimple   File: patch_config.py    Apache License 2.0 6 votes vote down vote up
def patch_config_as_nothrow(instance):
    if "NoThrow" in [instance.__name__, instance.__class__.__name__]:
        return instance

    if type(instance) == type:
        instance = types.new_class(instance.__name__ + "NoThrow", (instance, ), dict(metaclass=NoThrowMeta))
        for (k, v) in inspect.getmembers(instance):
            if not k.startswith("__") and type(v) == type:
                type.__setattr__(instance, k, patch_config_as_nothrow(v))
    else:
        for (k, v) in inspect.getmembers(instance.__class__):
            if not k.startswith("__") and type(v) == type:
                type.__setattr__(instance.__class__, k, patch_config_as_nothrow(v))
        instance.__class__ = type(instance.__class__.__name__ + "NoThrow", (instance.__class__, NoThrowBase), {})

    return instance 
Example 12
Project: Project-New-Reign---Nemesis-Main   Author: ShikyoKira   File: test_types.py    GNU General Public License v3.0 6 votes vote down vote up
def test_prepare_class(self):
        # Basic test of metaclass derivation
        expected_ns = {}
        class A(type):
            def __new__(*args, **kwargs):
                return type.__new__(*args, **kwargs)

            def __prepare__(*args):
                return expected_ns

        B = types.new_class("B", (object,))
        C = types.new_class("C", (object,), {"metaclass": A})

        # The most derived metaclass of D is A rather than type.
        meta, ns, kwds = types.prepare_class("D", (B, C), {"metaclass": type})
        self.assertIs(meta, A)
        self.assertIs(ns, expected_ns)
        self.assertEqual(len(kwds), 0) 
Example 13
Project: Project-New-Reign---Nemesis-Main   Author: ShikyoKira   File: test_types.py    GNU General Public License v3.0 6 votes vote down vote up
def test_metaclass_override_function(self):
        # Special case: the given metaclass isn't a class,
        # so there is no metaclass calculation.
        class A(metaclass=self.Meta):
            pass

        marker = object()
        def func(*args, **kwargs):
            return marker

        X = types.new_class("X", (), {"metaclass": func})
        Y = types.new_class("Y", (object,), {"metaclass": func})
        Z = types.new_class("Z", (A,), {"metaclass": func})
        self.assertIs(marker, X)
        self.assertIs(marker, Y)
        self.assertIs(marker, Z) 
Example 14
Project: Project-New-Reign---Nemesis-Main   Author: ShikyoKira   File: util.py    GNU General Public License v3.0 6 votes vote down vote up
def specialize_class(cls, kind, base=None, **kwargs):
    # XXX Support passing in submodule names--load (and cache) them?
    # That would clean up the test modules a bit more.
    if base is None:
        base = unittest.TestCase
    elif not isinstance(base, type):
        base = base[kind]
    name = '{}_{}'.format(kind, cls.__name__)
    bases = (cls, base)
    specialized = types.new_class(name, bases)
    specialized.__module__ = cls.__module__
    specialized._NAME = cls.__name__
    specialized._KIND = kind
    for attr, values in kwargs.items():
        value = values[kind]
        setattr(specialized, attr, value)
    return specialized 
Example 15
Project: cells   Author: AlesTsurko   File: test_types.py    MIT License 6 votes vote down vote up
def test_prepare_class(self):
        # Basic test of metaclass derivation
        expected_ns = {}
        class A(type):
            def __new__(*args, **kwargs):
                return type.__new__(*args, **kwargs)

            def __prepare__(*args):
                return expected_ns

        B = types.new_class("B", (object,))
        C = types.new_class("C", (object,), {"metaclass": A})

        # The most derived metaclass of D is A rather than type.
        meta, ns, kwds = types.prepare_class("D", (B, C), {"metaclass": type})
        self.assertIs(meta, A)
        self.assertIs(ns, expected_ns)
        self.assertEqual(len(kwds), 0) 
Example 16
Project: cells   Author: AlesTsurko   File: test_types.py    MIT License 6 votes vote down vote up
def test_metaclass_override_function(self):
        # Special case: the given metaclass isn't a class,
        # so there is no metaclass calculation.
        class A(metaclass=self.Meta):
            pass

        marker = object()
        def func(*args, **kwargs):
            return marker

        X = types.new_class("X", (), {"metaclass": func})
        Y = types.new_class("Y", (object,), {"metaclass": func})
        Z = types.new_class("Z", (A,), {"metaclass": func})
        self.assertIs(marker, X)
        self.assertIs(marker, Y)
        self.assertIs(marker, Z) 
Example 17
Project: cells   Author: AlesTsurko   File: util.py    MIT License 6 votes vote down vote up
def specialize_class(cls, kind, base=None, **kwargs):
    # XXX Support passing in submodule names--load (and cache) them?
    # That would clean up the test modules a bit more.
    if base is None:
        base = unittest.TestCase
    elif not isinstance(base, type):
        base = base[kind]
    name = '{}_{}'.format(kind, cls.__name__)
    bases = (cls, base)
    specialized = types.new_class(name, bases)
    specialized.__module__ = cls.__module__
    specialized._NAME = cls.__name__
    specialized._KIND = kind
    for attr, values in kwargs.items():
        value = values[kind]
        setattr(specialized, attr, value)
    return specialized 
Example 18
Project: NiujiaoDebugger   Author: MrSrc   File: test_types.py    GNU General Public License v3.0 5 votes vote down vote up
def test_new_class_basics(self):
        C = types.new_class("C")
        self.assertEqual(C.__name__, "C")
        self.assertEqual(C.__bases__, (object,)) 
Example 19
Project: NiujiaoDebugger   Author: MrSrc   File: test_types.py    GNU General Public License v3.0 5 votes vote down vote up
def test_new_class_subclass(self):
        C = types.new_class("C", (int,))
        self.assertTrue(issubclass(C, int)) 
Example 20
Project: NiujiaoDebugger   Author: MrSrc   File: test_types.py    GNU General Public License v3.0 5 votes vote down vote up
def test_new_class_meta(self):
        Meta = self.Meta
        settings = {"metaclass": Meta, "z": 2}
        # We do this twice to make sure the passed in dict isn't mutated
        for i in range(2):
            C = types.new_class("C" + str(i), (), settings)
            self.assertIsInstance(C, Meta)
            self.assertEqual(C.y, 1)
            self.assertEqual(C.z, 2) 
Example 21
Project: NiujiaoDebugger   Author: MrSrc   File: test_types.py    GNU General Public License v3.0 5 votes vote down vote up
def test_new_class_exec_body(self):
        Meta = self.Meta
        def func(ns):
            ns["x"] = 0
        C = types.new_class("C", (), {"metaclass": Meta, "z": 2}, func)
        self.assertIsInstance(C, Meta)
        self.assertEqual(C.x, 0)
        self.assertEqual(C.y, 1)
        self.assertEqual(C.z, 2) 
Example 22
Project: NiujiaoDebugger   Author: MrSrc   File: test_types.py    GNU General Public License v3.0 5 votes vote down vote up
def test_new_class_metaclass_keywords(self):
        #Test that keywords are passed to the metaclass:
        def meta_func(name, bases, ns, **kw):
            return name, bases, ns, kw
        res = types.new_class("X",
                              (int, object),
                              dict(metaclass=meta_func, x=0))
        self.assertEqual(res, ("X", (int, object), {}, {"x": 0})) 
Example 23
Project: NiujiaoDebugger   Author: MrSrc   File: test_types.py    GNU General Public License v3.0 5 votes vote down vote up
def test_new_class_meta_with_base(self):
        Meta = self.Meta
        def func(ns):
            ns["x"] = 0
        C = types.new_class(name="C",
                            bases=(int,),
                            kwds=dict(metaclass=Meta, z=2),
                            exec_body=func)
        self.assertTrue(issubclass(C, int))
        self.assertIsInstance(C, Meta)
        self.assertEqual(C.x, 0)
        self.assertEqual(C.y, 1)
        self.assertEqual(C.z, 2) 
Example 24
Project: NiujiaoDebugger   Author: MrSrc   File: test_types.py    GNU General Public License v3.0 5 votes vote down vote up
def test_new_class_with_mro_entry(self):
        class A: pass
        class C:
            def __mro_entries__(self, bases):
                return (A,)
        c = C()
        D = types.new_class('D', (c,), {})
        self.assertEqual(D.__bases__, (A,))
        self.assertEqual(D.__orig_bases__, (c,))
        self.assertEqual(D.__mro__, (D, A, object)) 
Example 25
Project: NiujiaoDebugger   Author: MrSrc   File: test_types.py    GNU General Public License v3.0 5 votes vote down vote up
def test_new_class_with_mro_entry_none(self):
        class A: pass
        class B: pass
        class C:
            def __mro_entries__(self, bases):
                return ()
        c = C()
        D = types.new_class('D', (A, c, B), {})
        self.assertEqual(D.__bases__, (A, B))
        self.assertEqual(D.__orig_bases__, (A, c, B))
        self.assertEqual(D.__mro__, (D, A, B, object)) 
Example 26
Project: NiujiaoDebugger   Author: MrSrc   File: test_types.py    GNU General Public License v3.0 5 votes vote down vote up
def test_new_class_with_mro_entry_error(self):
        class A: pass
        class C:
            def __mro_entries__(self, bases):
                return A
        c = C()
        with self.assertRaises(TypeError):
            types.new_class('D', (c,), {}) 
Example 27
Project: NiujiaoDebugger   Author: MrSrc   File: test_types.py    GNU General Public License v3.0 5 votes vote down vote up
def test_new_class_with_mro_entry_multiple(self):
        class A1: pass
        class A2: pass
        class B1: pass
        class B2: pass
        class A:
            def __mro_entries__(self, bases):
                return (A1, A2)
        class B:
            def __mro_entries__(self, bases):
                return (B1, B2)
        D = types.new_class('D', (A(), B()), {})
        self.assertEqual(D.__bases__, (A1, A2, B1, B2)) 
Example 28
Project: NiujiaoDebugger   Author: MrSrc   File: test_subclassinit.py    GNU General Public License v3.0 5 votes vote down vote up
def test_errors(self):
        class MyMeta(type):
            pass

        with self.assertRaises(TypeError):
            class MyClass(metaclass=MyMeta, otherarg=1):
                pass

        with self.assertRaises(TypeError):
            types.new_class("MyClass", (object,),
                            dict(metaclass=MyMeta, otherarg=1))
        types.prepare_class("MyClass", (object,),
                            dict(metaclass=MyMeta, otherarg=1))

        class MyMeta(type):
            def __init__(self, name, bases, namespace, otherarg):
                super().__init__(name, bases, namespace)

        with self.assertRaises(TypeError):
            class MyClass(metaclass=MyMeta, otherarg=1):
                pass

        class MyMeta(type):
            def __new__(cls, name, bases, namespace, otherarg):
                return super().__new__(cls, name, bases, namespace)

            def __init__(self, name, bases, namespace, otherarg):
                super().__init__(name, bases, namespace)
                self.otherarg = otherarg

        class MyClass(metaclass=MyMeta, otherarg=1):
            pass

        self.assertEqual(MyClass.otherarg, 1) 
Example 29
Project: TestSlide   Author: facebookincubator   File: __init__.py    MIT License 5 votes vote down vote up
def add_test_case(self, test_case, attr_name):
        """
        Add around hooks to context from given unittest.TestCase class. Only
        hooks such as setUp or tearDown will be called, no tests will be
        included.
        """

        def wrap_test_case(self, example):
            def test_test_slide(_):
                example()

            def exec_body(ns):
                ns.update({"test_test_slide": test_test_slide})

            # Build a child class of given TestCase, with a defined test that
            # will run TestSlide example.
            test_slide_test_case = types.new_class(
                "TestSlideTestCase", bases=(test_case,), exec_body=exec_body
            )

            # This suite will only contain TestSlide's example test.
            test_suite = unittest.TestLoader().loadTestsFromName(
                "test_test_slide", test_slide_test_case
            )
            setattr(self, attr_name, list(test_suite)[0])
            result = _TestSlideTestResult()
            test_suite(result=result)
            if not result.wasSuccessful():
                result.aggregated_exceptions.raise_correct_exception()

        self.around_functions.append(wrap_test_case) 
Example 30
Project: edgedb   Author: edgedb   File: tokens.py    Apache License 2.0 5 votes vote down vote up
def _gen_keyword_tokens():
    # Define keyword tokens

    mod = sys.modules[__name__]

    def clsexec(ns):
        ns['__module__'] = __name__
        return ns

    for token, _ in keywords.edgeql_keywords.values():
        clsname = 'T_{}'.format(token)
        clskwds = dict(metaclass=parsing.TokenMeta, token=token)
        cls = types.new_class(clsname, (Token,), clskwds, clsexec)
        setattr(mod, clsname, cls) 
Example 31
Project: cqp-sdk-for-py37-native   Author: crud-boy   File: test_types.py    GNU General Public License v2.0 5 votes vote down vote up
def test_new_class_basics(self):
        C = types.new_class("C")
        self.assertEqual(C.__name__, "C")
        self.assertEqual(C.__bases__, (object,)) 
Example 32
Project: cqp-sdk-for-py37-native   Author: crud-boy   File: test_types.py    GNU General Public License v2.0 5 votes vote down vote up
def test_new_class_subclass(self):
        C = types.new_class("C", (int,))
        self.assertTrue(issubclass(C, int)) 
Example 33
Project: cqp-sdk-for-py37-native   Author: crud-boy   File: test_types.py    GNU General Public License v2.0 5 votes vote down vote up
def test_new_class_meta(self):
        Meta = self.Meta
        settings = {"metaclass": Meta, "z": 2}
        # We do this twice to make sure the passed in dict isn't mutated
        for i in range(2):
            C = types.new_class("C" + str(i), (), settings)
            self.assertIsInstance(C, Meta)
            self.assertEqual(C.y, 1)
            self.assertEqual(C.z, 2) 
Example 34
Project: cqp-sdk-for-py37-native   Author: crud-boy   File: test_types.py    GNU General Public License v2.0 5 votes vote down vote up
def test_new_class_exec_body(self):
        Meta = self.Meta
        def func(ns):
            ns["x"] = 0
        C = types.new_class("C", (), {"metaclass": Meta, "z": 2}, func)
        self.assertIsInstance(C, Meta)
        self.assertEqual(C.x, 0)
        self.assertEqual(C.y, 1)
        self.assertEqual(C.z, 2) 
Example 35
Project: cqp-sdk-for-py37-native   Author: crud-boy   File: test_types.py    GNU General Public License v2.0 5 votes vote down vote up
def test_new_class_metaclass_keywords(self):
        #Test that keywords are passed to the metaclass:
        def meta_func(name, bases, ns, **kw):
            return name, bases, ns, kw
        res = types.new_class("X",
                              (int, object),
                              dict(metaclass=meta_func, x=0))
        self.assertEqual(res, ("X", (int, object), {}, {"x": 0})) 
Example 36
Project: cqp-sdk-for-py37-native   Author: crud-boy   File: test_types.py    GNU General Public License v2.0 5 votes vote down vote up
def test_new_class_meta_with_base(self):
        Meta = self.Meta
        def func(ns):
            ns["x"] = 0
        C = types.new_class(name="C",
                            bases=(int,),
                            kwds=dict(metaclass=Meta, z=2),
                            exec_body=func)
        self.assertTrue(issubclass(C, int))
        self.assertIsInstance(C, Meta)
        self.assertEqual(C.x, 0)
        self.assertEqual(C.y, 1)
        self.assertEqual(C.z, 2) 
Example 37
Project: cqp-sdk-for-py37-native   Author: crud-boy   File: test_types.py    GNU General Public License v2.0 5 votes vote down vote up
def test_new_class_with_mro_entry(self):
        class A: pass
        class C:
            def __mro_entries__(self, bases):
                return (A,)
        c = C()
        D = types.new_class('D', (c,), {})
        self.assertEqual(D.__bases__, (A,))
        self.assertEqual(D.__orig_bases__, (c,))
        self.assertEqual(D.__mro__, (D, A, object)) 
Example 38
Project: cqp-sdk-for-py37-native   Author: crud-boy   File: test_types.py    GNU General Public License v2.0 5 votes vote down vote up
def test_new_class_with_mro_entry_none(self):
        class A: pass
        class B: pass
        class C:
            def __mro_entries__(self, bases):
                return ()
        c = C()
        D = types.new_class('D', (A, c, B), {})
        self.assertEqual(D.__bases__, (A, B))
        self.assertEqual(D.__orig_bases__, (A, c, B))
        self.assertEqual(D.__mro__, (D, A, B, object)) 
Example 39
Project: cqp-sdk-for-py37-native   Author: crud-boy   File: test_types.py    GNU General Public License v2.0 5 votes vote down vote up
def test_new_class_with_mro_entry_error(self):
        class A: pass
        class C:
            def __mro_entries__(self, bases):
                return A
        c = C()
        with self.assertRaises(TypeError):
            types.new_class('D', (c,), {}) 
Example 40
Project: cqp-sdk-for-py37-native   Author: crud-boy   File: test_types.py    GNU General Public License v2.0 5 votes vote down vote up
def test_new_class_with_mro_entry_multiple(self):
        class A1: pass
        class A2: pass
        class B1: pass
        class B2: pass
        class A:
            def __mro_entries__(self, bases):
                return (A1, A2)
        class B:
            def __mro_entries__(self, bases):
                return (B1, B2)
        D = types.new_class('D', (A(), B()), {})
        self.assertEqual(D.__bases__, (A1, A2, B1, B2)) 
Example 41
Project: cqp-sdk-for-py37-native   Author: crud-boy   File: test_subclassinit.py    GNU General Public License v2.0 5 votes vote down vote up
def test_errors(self):
        class MyMeta(type):
            pass

        with self.assertRaises(TypeError):
            class MyClass(metaclass=MyMeta, otherarg=1):
                pass

        with self.assertRaises(TypeError):
            types.new_class("MyClass", (object,),
                            dict(metaclass=MyMeta, otherarg=1))
        types.prepare_class("MyClass", (object,),
                            dict(metaclass=MyMeta, otherarg=1))

        class MyMeta(type):
            def __init__(self, name, bases, namespace, otherarg):
                super().__init__(name, bases, namespace)

        with self.assertRaises(TypeError):
            class MyClass(metaclass=MyMeta, otherarg=1):
                pass

        class MyMeta(type):
            def __new__(cls, name, bases, namespace, otherarg):
                return super().__new__(cls, name, bases, namespace)

            def __init__(self, name, bases, namespace, otherarg):
                super().__init__(name, bases, namespace)
                self.otherarg = otherarg

        class MyClass(metaclass=MyMeta, otherarg=1):
            pass

        self.assertEqual(MyClass.otherarg, 1) 
Example 42
Project: doufo   Author: tech-pi   File: _dataclass.py    Apache License 2.0 5 votes vote down vote up
def dataclass(cls):
    base = attr.s(frozen=True, auto_attribs=True, slots=True)(cls)
    return types.new_class(base.__name__, (base, DataClass)) 
Example 43
Project: dingtalk-python   Author: blackmatrix7   File: exceptions.py    Apache License 2.0 5 votes vote down vote up
def __get__(self, instance, owner):
        supers = (DingTalkException, self.err_type, BaseException) \
            if self.err_type and self.err_type is not BaseException else (DingTalkException, BaseException)
        api_ex_cls = types.new_class('DingTalkException', supers, {}, lambda ns: ns)
        api_ex = api_ex_cls(err_msg=self.err_msg, err_code=self.err_code, http_code=self.http_code)
        return api_ex 
Example 44
Project: pyhow   Author: yoeo   File: objects.py    MIT License 5 votes vote down vote up
def delattr_builtin():
    """delattr: Delete an attribute from an object."""

    suv = types.new_class('Car')()
    suv.gear = 1
    delattr(suv, 'gear')
    try:
        suv.gear += 1
    except AttributeError:
        return "no gear to switch" 
Example 45
Project: pyhow   Author: yoeo   File: objects.py    MIT License 5 votes vote down vote up
def property_builtin():
    """property: Define getter setter and deleter for an attribute."""

    cars_horsepower = {}

    def get_power(car):
        """Get car horsepower."""
        if id(car) not in cars_horsepower:
            raise AttributeError('ask me later')
        return cars_horsepower[id(car)]

    def set_power(car, horsepower):
        """Set car horsepower."""
        cars_horsepower[id(car)] = (
            'goku power' if horsepower > 9000 else horsepower)

    def del_power(car):
        """Delete car horsepower."""
        del cars_horsepower[id(car)]

    car_class = types.new_class('Car')
    car_class.horsepower = property(get_power, set_power, del_power)

    formula_one = car_class()
    formula_one.horsepower = 9001
    return formula_one.horsepower 
Example 46
Project: pyhow   Author: yoeo   File: objects.py    MIT License 5 votes vote down vote up
def setattr_builtin():
    """setattr: Set an object attribute."""

    cabriolet = types.new_class('Car')()
    setattr(cabriolet, 'roof', False)
    return not cabriolet.roof and "feel the wind" 
Example 47
Project: pyhow   Author: yoeo   File: objects.py    MIT License 5 votes vote down vote up
def build_class():
    """__build_class__: Low level class maker. Prefer types.new_class(...)."""

    return __build_class__(lambda: None, 'NiceClass')().__class__.__name__ 
Example 48
Project: Project-New-Reign---Nemesis-Main   Author: ShikyoKira   File: test_types.py    GNU General Public License v3.0 5 votes vote down vote up
def test_new_class_basics(self):
        C = types.new_class("C")
        self.assertEqual(C.__name__, "C")
        self.assertEqual(C.__bases__, (object,)) 
Example 49
Project: Project-New-Reign---Nemesis-Main   Author: ShikyoKira   File: test_types.py    GNU General Public License v3.0 5 votes vote down vote up
def test_new_class_subclass(self):
        C = types.new_class("C", (int,))
        self.assertTrue(issubclass(C, int)) 
Example 50
Project: Project-New-Reign---Nemesis-Main   Author: ShikyoKira   File: test_types.py    GNU General Public License v3.0 5 votes vote down vote up
def test_new_class_meta(self):
        Meta = self.Meta
        settings = {"metaclass": Meta, "z": 2}
        # We do this twice to make sure the passed in dict isn't mutated
        for i in range(2):
            C = types.new_class("C" + str(i), (), settings)
            self.assertIsInstance(C, Meta)
            self.assertEqual(C.y, 1)
            self.assertEqual(C.z, 2)