當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。