当前位置: 首页>>代码示例>>Python>>正文


Python six.add_metaclass方法代码示例

本文整理汇总了Python中six.add_metaclass方法的典型用法代码示例。如果您正苦于以下问题:Python six.add_metaclass方法的具体用法?Python six.add_metaclass怎么用?Python six.add_metaclass使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在six的用法示例。


在下文中一共展示了six.add_metaclass方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: create_dummy_class

# 需要导入模块: import six [as 别名]
# 或者: from six import add_metaclass [as 别名]
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 
开发者ID:tensorpack,项目名称:dataflow,代码行数:27,代码来源:develop.py

示例2: function28

# 需要导入模块: import six [as 别名]
# 或者: from six import add_metaclass [as 别名]
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'] 
开发者ID:sofia-netsurv,项目名称:python-netsurv,代码行数:18,代码来源:invalid_sequence_index.py

示例3: test_genty_does_not_fail_when_trying_to_delete_attribute_defined_on_metaclass

# 需要导入模块: import six [as 别名]
# 或者: from six import add_metaclass [as 别名]
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)) 
开发者ID:box,项目名称:genty,代码行数:22,代码来源:test_genty.py

示例4: test_add_metaclass_nested

# 需要导入模块: import six [as 别名]
# 或者: from six import add_metaclass [as 别名]
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 
开发者ID:benjaminp,项目名称:six,代码行数:19,代码来源:test_six.py

示例5: test_parse_state_meta

# 需要导入模块: import six [as 别名]
# 或者: from six import add_metaclass [as 别名]
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') 
开发者ID:openstack,项目名称:oslo.policy,代码行数:24,代码来源:test_parser.py

示例6: check_resource_scopes_set

# 需要导入模块: import six [as 别名]
# 或者: from six import add_metaclass [as 别名]
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) 
开发者ID:HewlettPackard,项目名称:oneview-ansible,代码行数:27,代码来源:oneview.py

示例7: test_class_docstring

# 需要导入模块: import six [as 别名]
# 或者: from six import add_metaclass [as 别名]
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"
    ) 
开发者ID:rsokl,项目名称:custom_inherit,代码行数:30,代码来源:metaclass_test.py

示例8: Collection

# 需要导入模块: import six [as 别名]
# 或者: from six import add_metaclass [as 别名]
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 
开发者ID:vmarkovtsev,项目名称:plueprint,代码行数:40,代码来源:entities.py

示例9: test_invalid_metaclass

# 需要导入模块: import six [as 别名]
# 或者: from six import add_metaclass [as 别名]
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) 
开发者ID:sofia-netsurv,项目名称:python-netsurv,代码行数:34,代码来源:unittest_checker_typecheck.py

示例10: test__abstractclass

# 需要导入模块: import six [as 别名]
# 或者: from six import add_metaclass [as 别名]
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) 
开发者ID:hootnot,项目名称:oanda-api-v20,代码行数:37,代码来源:test_decorators.py

示例11: bayes

# 需要导入模块: import six [as 别名]
# 或者: from six import add_metaclass [as 别名]
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)) 
开发者ID:ferrine,项目名称:gelato,代码行数:29,代码来源:base.py

示例12: capture_objs

# 需要导入模块: import six [as 别名]
# 或者: from six import add_metaclass [as 别名]
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] 
开发者ID:zalando,项目名称:spilo,代码行数:10,代码来源:setup.py

示例13: record

# 需要导入模块: import six [as 别名]
# 或者: from six import add_metaclass [as 别名]
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 
开发者ID:amzn,项目名称:ion-python,代码行数:29,代码来源:util.py

示例14: prettyxml

# 需要导入模块: import six [as 别名]
# 或者: from six import add_metaclass [as 别名]
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 
开发者ID:whonore,项目名称:Coqtail,代码行数:11,代码来源:xmlInterface.py

示例15: test_no_name_exception

# 需要导入模块: import six [as 别名]
# 或者: from six import add_metaclass [as 别名]
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) 
开发者ID:openstack,项目名称:osprofiler,代码行数:8,代码来源:test_profiler.py


注:本文中的six.add_metaclass方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。