Python six.add_metaclass() Examples

The following are 24 code examples of six.add_metaclass(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module six , or try the search function .
Example #1
Source File: test_genty.py    From genty with Apache License 2.0 6 votes vote down vote up
def test_genty_does_not_fail_when_trying_to_delete_attribute_defined_on_metaclass(self):
        class SomeMeta(type):
            def __new__(mcs, name, bases, attributes):
                attributes['test_defined_in_metaclass'] = genty_dataset('foo')(mcs.test_defined_in_metaclass)
                # pylint:disable=bad-super-call
                generated_class = super(SomeMeta, mcs).__new__(mcs, name, bases, attributes)
                return generated_class

            @staticmethod
            def test_defined_in_metaclass():
                pass

        @genty
        @six.add_metaclass(SomeMeta)
        class SomeClass(object):
            pass

        instance = SomeClass()

        self.assertIn('test_defined_in_metaclass({0})'.format(repr('foo')), dir(instance)) 
Example #2
Source File: develop.py    From tensorpack with Apache License 2.0 6 votes vote down vote up
def create_dummy_class(klass, dependency):
    """
    When a dependency of a class is not available, create a dummy class which throws ImportError when used.

    Args:
        klass (str): name of the class.
        dependency (str): name of the dependency.

    Returns:
        class: a class object
    """
    assert not building_rtfd()

    class _DummyMetaClass(type):
        # throw error on class attribute access
        def __getattr__(_, __):
            raise AttributeError("Cannot import '{}', therefore '{}' is not available".format(dependency, klass))

    @six.add_metaclass(_DummyMetaClass)
    class _Dummy(object):
        # throw error on constructor
        def __init__(self, *args, **kwargs):
            raise ImportError("Cannot import '{}', therefore '{}' is not available".format(dependency, klass))

    return _Dummy 
Example #3
Source File: oneview.py    From oneview-ansible with Apache License 2.0 6 votes vote down vote up
def check_resource_scopes_set(self, state, fact_name, scope_uris):
        """
        The following implementation will work for resource_absent under check mode.
        Generic implementation of the scopes update PATCH for the OneView resources.
        It checks if the resource needs to be updated with the current scopes.
        This method is meant to be run after ensuring the present state.
        :arg dict state: Dict containing the data from the last state results in the resource.
            It needs to have the 'msg', 'changed', and 'ansible_facts' entries.
        :arg str fact_name: Name of the fact returned to the Ansible.
        :arg list scope_uris: List with all the scope URIs to be added to the resource.
        :return: A dictionary with the expected arguments for the AnsibleModule.exit_json
        """
        if scope_uris is None:
            scope_uris = []

        resource = state['ansible_facts'][fact_name]

        if resource.get('scopeUris') is None or set(resource['scopeUris']) != set(scope_uris):
            state['changed'] = True
            state['msg'] = self.MSG_UPDATED

        return state


# @six.add_metaclass(abc.ABCMeta) 
Example #4
Source File: test_parser.py    From oslo.policy with Apache License 2.0 6 votes vote down vote up
def test_parse_state_meta(self):
        @six.add_metaclass(_parser.ParseStateMeta)
        class FakeState(object):

            @_parser.reducer('a', 'b', 'c')
            @_parser.reducer('d', 'e', 'f')
            def reduce1(self):
                pass

            @_parser.reducer('g', 'h', 'i')
            def reduce2(self):
                pass

        self.assertTrue(hasattr(FakeState, 'reducers'))
        for reduction, reducer in FakeState.reducers:
            if (reduction == ['a', 'b', 'c'] or
                    reduction == ['d', 'e', 'f']):
                self.assertEqual('reduce1', reducer)
            elif reduction == ['g', 'h', 'i']:
                self.assertEqual('reduce2', reducer)
            else:
                self.fail('Unrecognized reducer discovered') 
Example #5
Source File: test_six.py    From six with MIT License 6 votes vote down vote up
def test_add_metaclass_nested():
    # Regression test for https://github.com/benjaminp/six/issues/259
    class Meta(type):
        pass

    class A:
        class B: pass

    expected = 'test_add_metaclass_nested.<locals>.A.B'

    assert A.B.__qualname__ == expected

    class A:
        @six.add_metaclass(Meta)
        class B: pass

    assert A.B.__qualname__ == expected 
Example #6
Source File: develop.py    From ADL with MIT License 6 votes vote down vote up
def create_dummy_class(klass, dependency):
    """
    When a dependency of a class is not available, create a dummy class which throws ImportError when used.

    Args:
        klass (str): name of the class.
        dependency (str): name of the dependency.

    Returns:
        class: a class object
    """
    assert not building_rtfd()

    class _DummyMetaClass(type):
        # throw error on class attribute access
        def __getattr__(_, __):
            raise AttributeError("Cannot import '{}', therefore '{}' is not available".format(dependency, klass))

    @six.add_metaclass(_DummyMetaClass)
    class _Dummy(object):
        # throw error on constructor
        def __init__(self, *args, **kwargs):
            raise ImportError("Cannot import '{}', therefore '{}' is not available".format(dependency, klass))

    return _Dummy 
Example #7
Source File: develop.py    From petridishnn with MIT License 6 votes vote down vote up
def create_dummy_class(klass, dependency):
    """
    When a dependency of a class is not available, create a dummy class which throws ImportError when used.

    Args:
        klass (str): name of the class.
        dependency (str): name of the dependency.

    Returns:
        class: a class object
    """
    assert not building_rtfd()

    class _DummyMetaClass(type):
        # throw error on class attribute access
        def __getattr__(_, __):
            raise AttributeError("Cannot import '{}', therefore '{}' is not available".format(dependency, klass))

    @six.add_metaclass(_DummyMetaClass)
    class _Dummy(object):
        # throw error on constructor
        def __init__(self, *args, **kwargs):
            raise ImportError("Cannot import '{}', therefore '{}' is not available".format(dependency, klass))

    return _Dummy 
Example #8
Source File: develop.py    From dataflow with Apache License 2.0 6 votes vote down vote up
def create_dummy_class(klass, dependency):
    """
    When a dependency of a class is not available, create a dummy class which throws ImportError when used.

    Args:
        klass (str): name of the class.
        dependency (str): name of the dependency.

    Returns:
        class: a class object
    """
    assert not building_rtfd()

    class _DummyMetaClass(type):
        # throw error on class attribute access
        def __getattr__(_, __):
            raise AttributeError("Cannot import '{}', therefore '{}' is not available".format(dependency, klass))

    @six.add_metaclass(_DummyMetaClass)
    class _Dummy(object):
        # throw error on constructor
        def __init__(self, *args, **kwargs):
            raise ImportError("Cannot import '{}', therefore '{}' is not available".format(dependency, klass))

    return _Dummy 
Example #9
Source File: invalid_sequence_index.py    From python-netsurv with MIT License 6 votes vote down vote up
def function28():
    """Don't emit for classes with the right implementation."""

    class Meta(type):
        def __getitem__(cls, arg):
            return 24

    @six.add_metaclass(Meta)
    class Works(object):
        pass

    @six.add_metaclass(Meta)
    class Error(list):
        pass

    return Works['hello'] + Error['hello'] 
Example #10
Source File: invalid_sequence_index.py    From python-netsurv with MIT License 6 votes vote down vote up
def function28():
    """Don't emit for classes with the right implementation."""

    class Meta(type):
        def __getitem__(cls, arg):
            return 24

    @six.add_metaclass(Meta)
    class Works(object):
        pass

    @six.add_metaclass(Meta)
    class Error(list):
        pass

    return Works['hello'] + Error['hello'] 
Example #11
Source File: test_decorators.py    From oanda-api-v20 with MIT License 5 votes vote down vote up
def test__abstractclass(self):

        @six.add_metaclass(ABCMeta)
        class Something(object):

            @abstractmethod
            def __init__(self, x=10):
                self.x = x

        @abstractclass
        class SomethingElse(Something):
            # derived classes from this class make use
            # of this class __init__
            # since this __init__ overrides the parent's
            # @abstractmethod instances could be created,
            # by making the class abstract with @abstractclass
            # this can't be done, derived classes can
            # ... that is the goal

            def __init__(self, x=10, y=20):
                super(SomethingElse, self).__init__(x)
                self.y = y

        class ABCDerived(SomethingElse):
            pass

        with self.assertRaises(TypeError):
            Something(x=20)
        with self.assertRaises(TypeError):
            SomethingElse(x=20, y=30)

        x = 20
        y = 30
        abcDerived = ABCDerived(x, y)
        self.assertEqual(abcDerived.x + abcDerived.y, x+y) 
Example #12
Source File: base.py    From gelato with MIT License 5 votes vote down vote up
def bayes(layercls, stack=1):
    try:
        issubcls = issubclass(layercls, lasagne.layers.base.Layer)
    except TypeError:
        raise TypeError('{} needs to be a Layer subclass'
                        .format(layercls))
    if issubcls:
        if type(layercls) is LayerModelMeta:
            raise TypeError('{} is already bayesian'
                            .format(layercls))
        else:
            @six.add_metaclass(LayerModelMeta)
            class BayesianAnalog(layercls, pm.Model):
                pass
            frm = inspect.stack()[stack]
            mod = inspect.getmodule(frm[0])
            if mod is None:
                modname = '__main__'
            else:
                modname = mod.__name__
            BayesianAnalog.__module__ = modname
            BayesianAnalog.__doc__ = layercls.__doc__
            BayesianAnalog.__name__ = layercls.__name__
            return BayesianAnalog
    else:
        raise TypeError('{} needs to be a Layer subclass'
                        .format(layercls)) 
Example #13
Source File: setup.py    From spilo with Apache License 2.0 5 votes vote down vote up
def capture_objs(cls):
    from six import add_metaclass
    module = inspect.getmodule(cls)
    name = cls.__name__
    keeper_class = add_metaclass(ObjKeeper)(cls)
    setattr(module, name, keeper_class)
    cls = getattr(module, name)
    return keeper_class.instances[cls] 
Example #14
Source File: util.py    From ion-python with Apache License 2.0 5 votes vote down vote up
def record(*fields):
    """Constructs a type that can be extended to create immutable, value types.

    Examples:
        A typical declaration looks like::

            class MyRecord(record('a', ('b', 1))):
                pass

        The above would make a sub-class of ``collections.namedtuple`` that was named ``MyRecord`` with
        a constructor that had the ``b`` field set to 1 by default.

    Note:
        This uses meta-class machinery to rewrite the inheritance hierarchy.
        This is done in order to make sure that the underlying ``namedtuple`` instance is
        bound to the right type name and to make sure that the synthetic class that is generated
        to enable this machinery is not enabled for sub-classes of a user's record class.

    Args:
        fields (list[str | (str, any)]): A sequence of str or pairs that
    """
    @six.add_metaclass(_RecordMetaClass)
    class RecordType(object):
        _record_sentinel = True
        _record_fields = fields

    return RecordType 
Example #15
Source File: unittest_checker_typecheck.py    From python-netsurv with MIT License 5 votes vote down vote up
def test_invalid_metaclass(self):
        module = astroid.parse(
            """
        import six

        class InvalidAsMetaclass(object):
            pass

        @six.add_metaclass(int)
        class FirstInvalid(object):
            pass

        @six.add_metaclass(InvalidAsMetaclass)
        class SecondInvalid(object):
            pass

        @six.add_metaclass(2)
        class ThirdInvalid(object):
            pass
        """
        )
        for class_obj, metaclass_name in (
            ("ThirdInvalid", "2"),
            ("SecondInvalid", "InvalidAsMetaclass"),
            ("FirstInvalid", "int"),
        ):
            classdef = module[class_obj]
            message = Message(
                "invalid-metaclass", node=classdef, args=(metaclass_name,)
            )
            with self.assertAddsMessages(message):
                self.checker.visit_classdef(classdef) 
Example #16
Source File: setup.py    From bonfire with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def capture_objs(cls):
    from six import add_metaclass
    module = inspect.getmodule(cls)
    name = cls.__name__
    keeper_class = add_metaclass(ObjKeeper)(cls)
    setattr(module, name, keeper_class)
    cls = getattr(module, name)
    return keeper_class.instances[cls] 
Example #17
Source File: xmlInterface.py    From Coqtail with MIT License 5 votes vote down vote up
def prettyxml(xml):
    # type: (bytes) -> Text
    """Pretty print XML for debugging."""
    xml = _unescape(xml)
    # No stubs for xml.dom.minidom
    return parseString(xml).toprettyxml()  # type: ignore[no-any-return]


# Mypy doesn't know the type of add_metaclass since it comes from the local six.py 
Example #18
Source File: test_profiler.py    From osprofiler with Apache License 2.0 5 votes vote down vote up
def test_no_name_exception(self):
        def define_class_with_no_name():
            @six.add_metaclass(profiler.TracedMeta)
            class FakeTraceWithMetaclassNoName(FakeTracedCls):
                pass
        self.assertRaises(TypeError, define_class_with_no_name, 1) 
Example #19
Source File: unittest_checker_typecheck.py    From python-netsurv with MIT License 5 votes vote down vote up
def test_invalid_metaclass(self):
        module = astroid.parse(
            """
        import six

        class InvalidAsMetaclass(object):
            pass

        @six.add_metaclass(int)
        class FirstInvalid(object):
            pass

        @six.add_metaclass(InvalidAsMetaclass)
        class SecondInvalid(object):
            pass

        @six.add_metaclass(2)
        class ThirdInvalid(object):
            pass
        """
        )
        for class_obj, metaclass_name in (
            ("ThirdInvalid", "2"),
            ("SecondInvalid", "InvalidAsMetaclass"),
            ("FirstInvalid", "int"),
        ):
            classdef = module[class_obj]
            message = Message(
                "invalid-metaclass", node=classdef, args=(metaclass_name,)
            )
            with self.assertAddsMessages(message):
                self.checker.visit_classdef(classdef) 
Example #20
Source File: test_baseutils.py    From os-win with Apache License 2.0 5 votes vote down vote up
def test_synchronized_meta(self, mock_rlock_cls):
        fake_cls = type('fake_cls', (object, ),
                        dict(method1=lambda x: None, method2=lambda y: None))
        fake_cls = six.add_metaclass(baseutils.SynchronizedMeta)(fake_cls)

        fake_cls().method1()
        fake_cls().method2()

        mock_rlock_cls.assert_called_once_with()
        self.assertEqual(2, mock_rlock_cls.return_value.__exit__.call_count) 
Example #21
Source File: entities.py    From plueprint with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def Collection(child_type):
    @add_metaclass(SelfParsingSectionRegistry)
    class Base(Section):
        NESTED_ATTRS = "_children",

        def __init__(self, parent, children):
            super(Base, self).__init__(parent)
            self._children = OrderedDict()
            for child in children:
                assert isinstance(child, child_type)
                if child.parent is None:
                    child._parent = self
                self._children[child.name] = child
            self.__dict__.update(self._children)

        def __iter__(self):
            for child in self._children.values():
                yield child

        def __len__(self):
            return len(self._children)

        def __getitem__(self, item):
            return self._children[item]

        @classmethod
        def parse_from_etree(cls, parent, node):
            if len(node) == 0 or node[0].tag != "ul":
                raise ValueError("Invalid format: %s" % cls.__name__)
            return cls(
                parent,
                (child_type.parse_from_etree(None, c) for c in node[0]))

        def __str__(self):
            return "%s with %d items" % (
                type(self).__name__, len(self._children))

    return Base 
Example #22
Source File: metaclass_test.py    From custom_inherit with MIT License 5 votes vote down vote up
def test_class_docstring():
    @add_metaclass(DocInheritMeta(style="numpy"))
    class Parent(object):
        """
        Parent class.

        Returns
        -------
        foo
        """

    class Mixin(object):
        """
        This is mixin which does something.

        """

    class Child(Mixin, Parent):
        """
        Attributes
        ----------
        bar
        """

    assert (
        getdoc(Child)
        == "This is mixin which does something.\n\nAttributes\n----------\nbar\n\nReturns\n-------\nfoo"
    ) 
Example #23
Source File: test_genty.py    From genty with Apache License 2.0 4 votes vote down vote up
def test_genty_properly_composes_dataset_methods_up_hierarchy(self):
        # Some test frameworks set attributes on test classes directly through metaclasses. pymox is an example.
        # This test ensures that genty still won't expand inherited tests twice.
        class SomeMeta(type):
            def __init__(cls, name, bases, d):
                for base in bases:
                    for attr_name in dir(base):
                        if attr_name not in d:
                            d[attr_name] = getattr(base, attr_name)

                for func_name, func in d.items():
                    if func_name.startswith('test') and callable(func):
                        setattr(cls, func_name, cls.wrap_method(func))

                # pylint:disable=bad-super-call
                super(SomeMeta, cls).__init__(name, bases, d)

            def wrap_method(cls, func):
                @functools.wraps(func)
                def wrapped(*args, **kwargs):
                    return func(*args, **kwargs)
                return wrapped

        @genty
        @six.add_metaclass(SomeMeta)
        class SomeParent(object):
            @genty_dataset(100, 10)
            def test_parent(self, val):
                return val + 1

        @genty
        class SomeChild(SomeParent):
            @genty_dataset('a', 'b')
            def test_child(self, val):
                return val + val

        instance = SomeChild()

        self.assertEqual(4, self._count_test_methods(SomeChild))
        self.assertEqual(101, getattr(instance, 'test_parent(100)')())
        self.assertEqual(11, getattr(instance, 'test_parent(10)')())
        self.assertEqual('aa', getattr(instance, "test_child({0})".format(repr('a')))())
        self.assertEqual('bb', getattr(instance, "test_child({0})".format(repr('b')))())

        entries = dict(six.iteritems(SomeChild.__dict__))
        self.assertEqual(4, len([meth for name, meth in six.iteritems(entries) if name.startswith('test')]))
        self.assertFalse(hasattr(instance, 'test_parent(100)(100)'), 'genty should not expand a test more than once')
        self.assertFalse(hasattr(instance, 'test_parent(100)(10)'), 'genty should not expand a test more than once')
        self.assertFalse(hasattr(instance, 'test_parent(100)(10)'), 'genty should not expand a test more than once')
        self.assertFalse(hasattr(instance, 'test_parent(10)(10)'), 'genty should not expand a test more than once')

        self.assertFalse(hasattr(instance, 'test_parent'), "original method should not exist")
        self.assertFalse(hasattr(instance, 'test_child'), "original method should not exist") 
Example #24
Source File: test_facts.py    From pyinfra with MIT License 4 votes vote down vote up
def make_fact_tests(fact_name):
    fact = FACTS[fact_name]()

    @six.add_metaclass(JsonTest)
    class TestTests(TestCase):
        jsontest_files = path.join('tests', 'facts', fact_name)
        jsontest_prefix = 'test_{0}_'.format(fact_name)

        def jsontest_function(self, test_name, test_data, fact=fact):
            short_fact = None

            if isinstance(fact, ShortFactBase):
                short_fact = fact
                fact = fact.fact()

            command_to_check = None

            if callable(fact.command):
                args = test_data.get('arg', [])
                if not isinstance(args, list):
                    args = [args]

                command = fact.command(*args)

                if args or 'command' in test_data:
                    command_to_check = command

            elif 'command' in test_data:
                command_to_check = fact.command

            if command_to_check:
                assert get_command_string(command_to_check) == test_data['command']

            data = fact.process(test_data['output'])
            if short_fact:
                data = short_fact.process_data(data)

            # Encode/decode data to ensure datetimes/etc become JSON
            data = json.loads(json.dumps(data, default=json_encode))
            try:
                assert data == test_data['fact']
            except AssertionError as e:
                print()
                print('--> GOT:\n', json.dumps(data, indent=4, default=json_encode))
                print('--> WANT:', json.dumps(
                    test_data['fact'], indent=4, default=json_encode,
                ))
                raise e

    TestTests.__name__ = 'Fact{0}'.format(fact_name)
    return TestTests


# Find available fact tests