Python six 模块,with_metaclass() 实例源码

我们从Python开源项目中,提取了以下36个代码示例,用于说明如何使用six.with_metaclass()

项目:zipline-chinese    作者:zhanghan1990    | 项目源码 | 文件源码
def setUpClass(cls):
        FinalABCMeta = final_meta_factory(ABCMeta)

        class ABCWithFinal(with_metaclass(FinalABCMeta, object)):
            a = final('ABCWithFinal: a')
            b = 'ABCWithFinal: b'

            @final
            def f(self):
                return 'ABCWithFinal: f'

            def g(self):
                return 'ABCWithFinal: g'

            @abstractmethod
            def h(self):
                raise NotImplementedError('h')

        cls.class_ = ABCWithFinal
项目:zipline-chinese    作者:zhanghan1990    | 项目源码 | 文件源码
def test_subclass_setattr(self):
        """
        Tests that subclasses don't destroy the __setattr__.
        """
        class ClassWithFinal(with_metaclass(FinalMeta, object)):
            @final
            def f(self):
                return 'ClassWithFinal: f'

        class SubClass(ClassWithFinal):
            def __init__(self):
                self.a = 'a'

        SubClass()
        self.assertEqual(SubClass().a, 'a')
        self.assertEqual(SubClass().f(), 'ClassWithFinal: f')
项目:catalyst    作者:enigmampc    | 项目源码 | 文件源码
def with_metaclasses(metaclasses, *bases):
    """Make a class inheriting from ``bases`` whose metaclass inherits from
    all of ``metaclasses``.

    Like :func:`six.with_metaclass`, but allows multiple metaclasses.

    Parameters
    ----------
    metaclasses : iterable[type]
        A tuple of types to use as metaclasses.
    *bases : tuple[type]
        A tuple of types to use as bases.

    Returns
    -------
    base : type
        A subtype of ``bases`` whose metaclass is a subtype of ``metaclasses``.

    Notes
    -----
    The metaclasses must be written to support cooperative multiple
    inheritance. This means that they must delegate all calls to ``super()``
    instead of inlining their super class by name.
    """
    return six.with_metaclass(compose_types(*metaclasses), *bases)
项目:catalyst    作者:enigmampc    | 项目源码 | 文件源码
def setUpClass(cls):
        FinalABCMeta = compose_types(FinalMeta, ABCMeta)

        class ABCWithFinal(with_metaclass(FinalABCMeta, object)):
            a = final('ABCWithFinal: a')
            b = 'ABCWithFinal: b'

            @final
            def f(self):
                return 'ABCWithFinal: f'

            def g(self):
                return 'ABCWithFinal: g'

            @abstractmethod
            def h(self):
                raise NotImplementedError('h')

        cls.class_ = ABCWithFinal
项目:catalyst    作者:enigmampc    | 项目源码 | 文件源码
def test_subclass_setattr(self):
        """
        Tests that subclasses don't destroy the __setattr__.
        """
        class ClassWithFinal(with_metaclass(FinalMeta, object)):
            @final
            def f(self):
                return 'ClassWithFinal: f'

        class SubClass(ClassWithFinal):
            def __init__(self):
                self.a = 'a'

        SubClass()
        self.assertEqual(SubClass().a, 'a')
        self.assertEqual(SubClass().f(), 'ClassWithFinal: f')
项目:obsoleted-vpduserv    作者:InfraSIM    | 项目源码 | 文件源码
def test_with_metaclass():
    class Meta(type):
        pass
    class X(six.with_metaclass(Meta)):
        pass
    assert type(X) is Meta
    assert issubclass(X, object)
    class Base(object):
        pass
    class X(six.with_metaclass(Meta, Base)):
        pass
    assert type(X) is Meta
    assert issubclass(X, Base)
    class Base2(object):
        pass
    class X(six.with_metaclass(Meta, Base, Base2)):
        pass
    assert type(X) is Meta
    assert issubclass(X, Base)
    assert issubclass(X, Base2)
    assert X.__mro__ == (X, Base, Base2, object)
项目:Deploy_XXNET_Server    作者:jzp820927    | 项目源码 | 文件源码
def test_with_metaclass():
    class Meta(type):
        pass
    class X(six.with_metaclass(Meta)):
        pass
    assert type(X) is Meta
    assert issubclass(X, object)
    class Base(object):
        pass
    class X(six.with_metaclass(Meta, Base)):
        pass
    assert type(X) is Meta
    assert issubclass(X, Base)
    class Base2(object):
        pass
    class X(six.with_metaclass(Meta, Base, Base2)):
        pass
    assert type(X) is Meta
    assert issubclass(X, Base)
    assert issubclass(X, Base2)
    assert X.__mro__ == (X, Base, Base2, object)
项目:six    作者:benjaminp    | 项目源码 | 文件源码
def test_with_metaclass_prepare():
    """Test that with_metaclass causes Meta.__prepare__ to be called with the correct arguments."""

    class MyDict(dict):
        pass

    class Meta(type):

        @classmethod
        def __prepare__(cls, name, bases):
            namespace = MyDict(super().__prepare__(name, bases), cls=cls, bases=bases)
            namespace['namespace'] = namespace
            return namespace

    class Base(object):
        pass

    bases = (Base,)

    class X(six.with_metaclass(Meta, *bases)):
        pass

    assert getattr(X, 'cls', type) is Meta
    assert getattr(X, 'bases', ()) == bases
    assert isinstance(getattr(X, 'namespace', {}), MyDict)
项目:googleURLParser    作者:randomaccess3    | 项目源码 | 文件源码
def testParsingFlatClassWithExplicitClassDeclaration(self):
    """Test that the generated class can parse a flat message."""
    # TODO(xiaofeng): This test fails with cpp implemetnation in the call
    # of six.with_metaclass(). The other two callsites of with_metaclass
    # in this file are both excluded from cpp test, so it might be expected
    # to fail. Need someone more familiar with the python code to take a
    # look at this.
    if api_implementation.Type() != 'python':
      return
    file_descriptor = descriptor_pb2.FileDescriptorProto()
    file_descriptor.ParseFromString(self._GetSerializedFileDescriptor('A'))
    msg_descriptor = descriptor.MakeDescriptor(
        file_descriptor.message_type[0])

    class MessageClass(six.with_metaclass(reflection.GeneratedProtocolMessageType, message.Message)):
      DESCRIPTOR = msg_descriptor
    msg = MessageClass()
    msg_str = (
        'flat: 0 '
        'flat: 1 '
        'flat: 2 ')
    text_format.Merge(msg_str, msg)
    self.assertEqual(msg.flat, [0, 1, 2])
项目:zipline-chinese    作者:zhanghan1990    | 项目源码 | 文件源码
def setUpClass(cls):
        class ClassWithFinal(with_metaclass(FinalMeta, object)):
            a = final('ClassWithFinal: a')
            b = 'ClassWithFinal: b'

            @final
            def f(self):
                return 'ClassWithFinal: f'

            def g(self):
                return 'ClassWithFinal: g'

        cls.class_ = ClassWithFinal
项目:zipline-chinese    作者:zhanghan1990    | 项目源码 | 文件源码
def test_final_classmethod(self):

        class ClassWithClassMethod(with_metaclass(FinalMeta, object)):
            count = 0

            @final
            @classmethod
            def f(cls):
                cls.count += 1
                return cls.count

        with self.assertRaises(TypeError):
            class ClassOverridingClassMethod(ClassWithClassMethod):
                @classmethod
                def f(cls):
                    return "Oh Noes!"

        with self.assertRaises(TypeError):
            ClassWithClassMethod.f = lambda cls: 0

        self.assertEqual(ClassWithClassMethod.f(), 1)
        self.assertEqual(ClassWithClassMethod.f(), 2)
        self.assertEqual(ClassWithClassMethod.f(), 3)

        instance = ClassWithClassMethod()

        with self.assertRaises(TypeError):
            instance.f = lambda cls: 0

        self.assertEqual(ClassWithClassMethod.f(), 4)
        self.assertEqual(ClassWithClassMethod.f(), 5)
        self.assertEqual(ClassWithClassMethod.f(), 6)
项目:catalyst    作者:enigmampc    | 项目源码 | 文件源码
def setUpClass(cls):
        class ClassWithFinal(with_metaclass(FinalMeta, object)):
            a = final('ClassWithFinal: a')
            b = 'ClassWithFinal: b'

            @final
            def f(self):
                return 'ClassWithFinal: f'

            def g(self):
                return 'ClassWithFinal: g'

        cls.class_ = ClassWithFinal
项目:catalyst    作者:enigmampc    | 项目源码 | 文件源码
def test_final_classmethod(self):

        class ClassWithClassMethod(with_metaclass(FinalMeta, object)):
            count = 0

            @final
            @classmethod
            def f(cls):
                cls.count += 1
                return cls.count

        with self.assertRaises(TypeError):
            class ClassOverridingClassMethod(ClassWithClassMethod):
                @classmethod
                def f(cls):
                    return "Oh Noes!"

        with self.assertRaises(TypeError):
            ClassWithClassMethod.f = lambda cls: 0

        self.assertEqual(ClassWithClassMethod.f(), 1)
        self.assertEqual(ClassWithClassMethod.f(), 2)
        self.assertEqual(ClassWithClassMethod.f(), 3)

        instance = ClassWithClassMethod()

        with self.assertRaises(TypeError):
            instance.f = lambda cls: 0

        self.assertEqual(ClassWithClassMethod.f(), 4)
        self.assertEqual(ClassWithClassMethod.f(), 5)
        self.assertEqual(ClassWithClassMethod.f(), 6)
项目:MDT    作者:cbclab    | 项目源码 | 文件源码
def method_binding_meta(template, *bases):
    """Adds all bound functions from the ComponentTemplate to the class being constructed.

     This returns a metaclass similar to the with_metaclass of the six library.

     Args:
         template (ComponentTemplate): the component config with the bound_methods attribute which we will all add
            to the attributes of the to creating class.
     """
    class ApplyMethodBinding(type):
        def __new__(mcs, name, bases, attributes):
            attributes.update(template.bound_methods)
            return super(ApplyMethodBinding, mcs).__new__(mcs, name, bases, attributes)

    return with_metaclass(ApplyMethodBinding, *bases)
项目:tossi    作者:what-studio    | 项目源码 | 文件源码
def singleton_particle(*bases):
    """Defines a singleton instance immediately when defining the class.  The
    name of the class will refer the instance instead.
    """
    return with_metaclass(SingletonParticleMeta, SingletonParticle, *bases)
项目:tossi    作者:what-studio    | 项目源码 | 文件源码
def test_singleton_error():
    with pytest.raises(TypeError):
        class Fail(with_metaclass(SingletonParticleMeta, object)):
            pass
项目:Vector-Tiles-Reader-QGIS-Plugin    作者:geometalab    | 项目源码 | 文件源码
def testHandWrittenReflection(self):
    # Hand written extensions are only supported by the pure-Python
    # implementation of the API.
    if api_implementation.Type() != 'python':
      return

    FieldDescriptor = descriptor.FieldDescriptor
    foo_field_descriptor = FieldDescriptor(
        name='foo_field', full_name='MyProto.foo_field',
        index=0, number=1, type=FieldDescriptor.TYPE_INT64,
        cpp_type=FieldDescriptor.CPPTYPE_INT64,
        label=FieldDescriptor.LABEL_OPTIONAL, default_value=0,
        containing_type=None, message_type=None, enum_type=None,
        is_extension=False, extension_scope=None,
        options=descriptor_pb2.FieldOptions())
    mydescriptor = descriptor.Descriptor(
        name='MyProto', full_name='MyProto', filename='ignored',
        containing_type=None, nested_types=[], enum_types=[],
        fields=[foo_field_descriptor], extensions=[],
        options=descriptor_pb2.MessageOptions())
    class MyProtoClass(six.with_metaclass(reflection.GeneratedProtocolMessageType, message.Message)):
      DESCRIPTOR = mydescriptor
    myproto_instance = MyProtoClass()
    self.assertEqual(0, myproto_instance.foo_field)
    self.assertTrue(not myproto_instance.HasField('foo_field'))
    myproto_instance.foo_field = 23
    self.assertEqual(23, myproto_instance.foo_field)
    self.assertTrue(myproto_instance.HasField('foo_field'))
项目:Vector-Tiles-Reader-QGIS-Plugin    作者:geometalab    | 项目源码 | 文件源码
def testParsingFlatClassWithExplicitClassDeclaration(self):
    """Test that the generated class can parse a flat message."""
    # TODO(xiaofeng): This test fails with cpp implemetnation in the call
    # of six.with_metaclass(). The other two callsites of with_metaclass
    # in this file are both excluded from cpp test, so it might be expected
    # to fail. Need someone more familiar with the python code to take a
    # look at this.
    if api_implementation.Type() != 'python':
      return
    file_descriptor = descriptor_pb2.FileDescriptorProto()
    file_descriptor.ParseFromString(self._GetSerializedFileDescriptor('A'))
    msg_descriptor = descriptor.MakeDescriptor(
        file_descriptor.message_type[0])

    class MessageClass(six.with_metaclass(reflection.GeneratedProtocolMessageType, message.Message)):
      DESCRIPTOR = msg_descriptor
    msg = MessageClass()
    msg_str = (
        'flat: 0 '
        'flat: 1 '
        'flat: 2 ')
    text_format.Merge(msg_str, msg)
    self.assertEqual(msg.flat, [0, 1, 2])
项目:shelter    作者:seznam    | 项目源码 | 文件源码
def test_add_logger_meta():

    class DummyClass(six.with_metaclass(AddLoggerMeta, object)):
        pass

    assert isinstance(DummyClass.logger, logging.Logger)
    assert DummyClass.logger.name == 'tests.test_utils_logging.DummyClass'
项目:coremltools    作者:apple    | 项目源码 | 文件源码
def testHandWrittenReflection(self):
    # Hand written extensions are only supported by the pure-Python
    # implementation of the API.
    if api_implementation.Type() != 'python':
      return

    FieldDescriptor = descriptor.FieldDescriptor
    foo_field_descriptor = FieldDescriptor(
        name='foo_field', full_name='MyProto.foo_field',
        index=0, number=1, type=FieldDescriptor.TYPE_INT64,
        cpp_type=FieldDescriptor.CPPTYPE_INT64,
        label=FieldDescriptor.LABEL_OPTIONAL, default_value=0,
        containing_type=None, message_type=None, enum_type=None,
        is_extension=False, extension_scope=None,
        options=descriptor_pb2.FieldOptions())
    mydescriptor = descriptor.Descriptor(
        name='MyProto', full_name='MyProto', filename='ignored',
        containing_type=None, nested_types=[], enum_types=[],
        fields=[foo_field_descriptor], extensions=[],
        options=descriptor_pb2.MessageOptions())
    class MyProtoClass(six.with_metaclass(reflection.GeneratedProtocolMessageType, message.Message)):
      DESCRIPTOR = mydescriptor
    myproto_instance = MyProtoClass()
    self.assertEqual(0, myproto_instance.foo_field)
    self.assertTrue(not myproto_instance.HasField('foo_field'))
    myproto_instance.foo_field = 23
    self.assertEqual(23, myproto_instance.foo_field)
    self.assertTrue(myproto_instance.HasField('foo_field'))
项目:coremltools    作者:apple    | 项目源码 | 文件源码
def testParsingFlatClassWithExplicitClassDeclaration(self):
    """Test that the generated class can parse a flat message."""
    # TODO(xiaofeng): This test fails with cpp implemetnation in the call
    # of six.with_metaclass(). The other two callsites of with_metaclass
    # in this file are both excluded from cpp test, so it might be expected
    # to fail. Need someone more familiar with the python code to take a
    # look at this.
    if api_implementation.Type() != 'python':
      return
    file_descriptor = descriptor_pb2.FileDescriptorProto()
    file_descriptor.ParseFromString(self._GetSerializedFileDescriptor('A'))
    msg_descriptor = descriptor.MakeDescriptor(
        file_descriptor.message_type[0])

    class MessageClass(six.with_metaclass(reflection.GeneratedProtocolMessageType, message.Message)):
      DESCRIPTOR = msg_descriptor
    msg = MessageClass()
    msg_str = (
        'flat: 0 '
        'flat: 1 '
        'flat: 2 ')
    text_format.Merge(msg_str, msg)
    self.assertEqual(msg.flat, [0, 1, 2])
项目:go2mapillary    作者:enricofer    | 项目源码 | 文件源码
def testHandWrittenReflection(self):
    # Hand written extensions are only supported by the pure-Python
    # implementation of the API.
    if api_implementation.Type() != 'python':
      return

    FieldDescriptor = descriptor.FieldDescriptor
    foo_field_descriptor = FieldDescriptor(
        name='foo_field', full_name='MyProto.foo_field',
        index=0, number=1, type=FieldDescriptor.TYPE_INT64,
        cpp_type=FieldDescriptor.CPPTYPE_INT64,
        label=FieldDescriptor.LABEL_OPTIONAL, default_value=0,
        containing_type=None, message_type=None, enum_type=None,
        is_extension=False, extension_scope=None,
        options=descriptor_pb2.FieldOptions())
    mydescriptor = descriptor.Descriptor(
        name='MyProto', full_name='MyProto', filename='ignored',
        containing_type=None, nested_types=[], enum_types=[],
        fields=[foo_field_descriptor], extensions=[],
        options=descriptor_pb2.MessageOptions())
    class MyProtoClass(six.with_metaclass(reflection.GeneratedProtocolMessageType, message.Message)):
      DESCRIPTOR = mydescriptor
    myproto_instance = MyProtoClass()
    self.assertEqual(0, myproto_instance.foo_field)
    self.assertTrue(not myproto_instance.HasField('foo_field'))
    myproto_instance.foo_field = 23
    self.assertEqual(23, myproto_instance.foo_field)
    self.assertTrue(myproto_instance.HasField('foo_field'))
项目:go2mapillary    作者:enricofer    | 项目源码 | 文件源码
def testParsingFlatClassWithExplicitClassDeclaration(self):
    """Test that the generated class can parse a flat message."""
    # TODO(xiaofeng): This test fails with cpp implemetnation in the call
    # of six.with_metaclass(). The other two callsites of with_metaclass
    # in this file are both excluded from cpp test, so it might be expected
    # to fail. Need someone more familiar with the python code to take a
    # look at this.
    if api_implementation.Type() != 'python':
      return
    file_descriptor = descriptor_pb2.FileDescriptorProto()
    file_descriptor.ParseFromString(self._GetSerializedFileDescriptor('A'))
    msg_descriptor = descriptor.MakeDescriptor(
        file_descriptor.message_type[0])

    class MessageClass(six.with_metaclass(reflection.GeneratedProtocolMessageType, message.Message)):
      DESCRIPTOR = msg_descriptor
    msg = MessageClass()
    msg_str = (
        'flat: 0 '
        'flat: 1 '
        'flat: 2 ')
    text_format.Merge(msg_str, msg)
    self.assertEqual(msg.flat, [0, 1, 2])
项目:mes    作者:osess    | 项目源码 | 文件源码
def _get_subfield_superclass():
    # hardcore trick to support django < 1.3 - there was something wrong with
    # inheritance and SubfieldBase before django 1.3
    # see https://github.com/django/django/commit/222c73261650201f5ce99e8dd4b1ce0d30a69eb4
    if django.VERSION < (1,3):
        return models.Field
    return six.with_metaclass(models.SubfieldBase, models.Field)
项目:six    作者:benjaminp    | 项目源码 | 文件源码
def test_with_metaclass():
    class Meta(type):
        pass
    class X(six.with_metaclass(Meta)):
        pass
    assert type(X) is Meta
    assert issubclass(X, object)
    class Base(object):
        pass
    class X(six.with_metaclass(Meta, Base)):
        pass
    assert type(X) is Meta
    assert issubclass(X, Base)
    class Base2(object):
        pass
    class X(six.with_metaclass(Meta, Base, Base2)):
        pass
    assert type(X) is Meta
    assert issubclass(X, Base)
    assert issubclass(X, Base2)
    assert X.__mro__ == (X, Base, Base2, object)
    class X(six.with_metaclass(Meta)):
        pass
    class MetaSub(Meta):
        pass
    class Y(six.with_metaclass(MetaSub, X)):
        pass
    assert type(Y) is MetaSub
    assert Y.__mro__ == (Y, X, object)
项目:rpcDemo    作者:Tangxinwei    | 项目源码 | 文件源码
def testHandWrittenReflection(self):
    # Hand written extensions are only supported by the pure-Python
    # implementation of the API.
    if api_implementation.Type() != 'python':
      return

    FieldDescriptor = descriptor.FieldDescriptor
    foo_field_descriptor = FieldDescriptor(
        name='foo_field', full_name='MyProto.foo_field',
        index=0, number=1, type=FieldDescriptor.TYPE_INT64,
        cpp_type=FieldDescriptor.CPPTYPE_INT64,
        label=FieldDescriptor.LABEL_OPTIONAL, default_value=0,
        containing_type=None, message_type=None, enum_type=None,
        is_extension=False, extension_scope=None,
        options=descriptor_pb2.FieldOptions())
    mydescriptor = descriptor.Descriptor(
        name='MyProto', full_name='MyProto', filename='ignored',
        containing_type=None, nested_types=[], enum_types=[],
        fields=[foo_field_descriptor], extensions=[],
        options=descriptor_pb2.MessageOptions())
    class MyProtoClass(six.with_metaclass(reflection.GeneratedProtocolMessageType, message.Message)):
      DESCRIPTOR = mydescriptor
    myproto_instance = MyProtoClass()
    self.assertEqual(0, myproto_instance.foo_field)
    self.assertTrue(not myproto_instance.HasField('foo_field'))
    myproto_instance.foo_field = 23
    self.assertEqual(23, myproto_instance.foo_field)
    self.assertTrue(myproto_instance.HasField('foo_field'))
项目:rpcDemo    作者:Tangxinwei    | 项目源码 | 文件源码
def testParsingFlatClassWithExplicitClassDeclaration(self):
    """Test that the generated class can parse a flat message."""
    # TODO(xiaofeng): This test fails with cpp implemetnation in the call
    # of six.with_metaclass(). The other two callsites of with_metaclass
    # in this file are both excluded from cpp test, so it might be expected
    # to fail. Need someone more familiar with the python code to take a
    # look at this.
    if api_implementation.Type() != 'python':
      return
    file_descriptor = descriptor_pb2.FileDescriptorProto()
    file_descriptor.ParseFromString(self._GetSerializedFileDescriptor('A'))
    msg_descriptor = descriptor.MakeDescriptor(
        file_descriptor.message_type[0])

    class MessageClass(six.with_metaclass(reflection.GeneratedProtocolMessageType, message.Message)):
      DESCRIPTOR = msg_descriptor
    msg = MessageClass()
    msg_str = (
        'flat: 0 '
        'flat: 1 '
        'flat: 2 ')
    text_format.Merge(msg_str, msg)
    self.assertEqual(msg.flat, [0, 1, 2])
项目:googleURLParser    作者:randomaccess3    | 项目源码 | 文件源码
def testHandWrittenReflection(self):
    # Hand written extensions are only supported by the pure-Python
    # implementation of the API.
    if api_implementation.Type() != 'python':
      return

    FieldDescriptor = descriptor.FieldDescriptor
    foo_field_descriptor = FieldDescriptor(
        name='foo_field', full_name='MyProto.foo_field',
        index=0, number=1, type=FieldDescriptor.TYPE_INT64,
        cpp_type=FieldDescriptor.CPPTYPE_INT64,
        label=FieldDescriptor.LABEL_OPTIONAL, default_value=0,
        containing_type=None, message_type=None, enum_type=None,
        is_extension=False, extension_scope=None,
        options=descriptor_pb2.FieldOptions())
    mydescriptor = descriptor.Descriptor(
        name='MyProto', full_name='MyProto', filename='ignored',
        containing_type=None, nested_types=[], enum_types=[],
        fields=[foo_field_descriptor], extensions=[],
        options=descriptor_pb2.MessageOptions())
    class MyProtoClass(six.with_metaclass(reflection.GeneratedProtocolMessageType, message.Message)):
      DESCRIPTOR = mydescriptor
    myproto_instance = MyProtoClass()
    self.assertEqual(0, myproto_instance.foo_field)
    self.assertTrue(not myproto_instance.HasField('foo_field'))
    myproto_instance.foo_field = 23
    self.assertEqual(23, myproto_instance.foo_field)
    self.assertTrue(myproto_instance.HasField('foo_field'))
项目:django-rest-easy    作者:Telmediq    | 项目源码 | 文件源码
def test_field_inheritance(self):
        class Mock(object):
            a = {}

        RegisteredCreator.inherit_fields = True
        RegisteredCreator.register = BaseRegister()

        class Test(six.with_metaclass(RegisteredCreator, Mock)):
            pass

        self.assertEqual(Mock.a, Test.a)
        RegisteredCreator.inherit_fields = False
项目:django-rest-easy    作者:Telmediq    | 项目源码 | 文件源码
def test_serializer_field_inheritance(self):
        class Mock(object):
            a = {}

        SerializerCreator.inherit_fields = True

        class Test(six.with_metaclass(SerializerCreator, Mock)):
            __abstract__ = True

        self.assertEqual(Mock.a, Test.a)
        SerializerCreator.inherit_fields = False
项目:filters    作者:eflglobal    | 项目源码 | 文件源码
def filter_macro(func, *args, **kwargs):
    """
    Promotes a function that returns a filter into its own filter type.

    Example::

        @filter_macro
        def String():
            return Unicode | Strip | NotEmpty

        # You can now use `String` anywhere you would use a regular Filter:
        (String | Split(':')).apply('...')

    You can also use ``filter_macro`` to create partials, allowing you to
    preset one or more initialization arguments::

        Minor = filter_macro(Max, max_value=18, inclusive=False)
        Minor(inclusive=True).apply(18)
    """
    filter_partial = partial(func, *args, **kwargs)

    class FilterMacroMeta(FilterMeta):
        @staticmethod
        def __new__(mcs, name, bases, attrs):
            # This is as close as we can get to running
            # ``update_wrapper`` on a type.
            for attr in WRAPPER_ASSIGNMENTS:
                if hasattr(func, attr):
                    attrs[attr] = getattr(func, attr)

            # Note that we ignore the ``name`` argument, passing in
            # ``func.__name__`` instead.
            return super(FilterMacroMeta, mcs)\
                .__new__(mcs, func.__name__, bases, attrs)

        def __call__(cls, *runtime_args, **runtime_kwargs):
            return filter_partial(*runtime_args, **runtime_kwargs)

    class FilterMacro(with_metaclass(FilterMacroMeta, FilterMacroType)):
        # This method will probably never get called due to overloaded
        # ``__call__`` in the metaclass, but just in case, we'll include
        # it because it is an abstract method in `BaseFilter`.
        def _apply(self, value):
            # noinspection PyProtectedMember
            return self.__class__()._apply(value)

    return FilterMacro
项目:Vector-Tiles-Reader-QGIS-Plugin    作者:geometalab    | 项目源码 | 文件源码
def testDescriptorProtoSupport(self):
    # Hand written descriptors/reflection are only supported by the pure-Python
    # implementation of the API.
    if api_implementation.Type() != 'python':
      return

    def AddDescriptorField(proto, field_name, field_type):
      AddDescriptorField.field_index += 1
      new_field = proto.field.add()
      new_field.name = field_name
      new_field.type = field_type
      new_field.number = AddDescriptorField.field_index
      new_field.label = descriptor_pb2.FieldDescriptorProto.LABEL_OPTIONAL

    AddDescriptorField.field_index = 0

    desc_proto = descriptor_pb2.DescriptorProto()
    desc_proto.name = 'Car'
    fdp = descriptor_pb2.FieldDescriptorProto
    AddDescriptorField(desc_proto, 'name', fdp.TYPE_STRING)
    AddDescriptorField(desc_proto, 'year', fdp.TYPE_INT64)
    AddDescriptorField(desc_proto, 'automatic', fdp.TYPE_BOOL)
    AddDescriptorField(desc_proto, 'price', fdp.TYPE_DOUBLE)
    # Add a repeated field
    AddDescriptorField.field_index += 1
    new_field = desc_proto.field.add()
    new_field.name = 'owners'
    new_field.type = fdp.TYPE_STRING
    new_field.number = AddDescriptorField.field_index
    new_field.label = descriptor_pb2.FieldDescriptorProto.LABEL_REPEATED

    desc = descriptor.MakeDescriptor(desc_proto)
    self.assertTrue('name' in desc.fields_by_name)
    self.assertTrue('year' in desc.fields_by_name)
    self.assertTrue('automatic' in desc.fields_by_name)
    self.assertTrue('price' in desc.fields_by_name)
    self.assertTrue('owners' in desc.fields_by_name)

    class CarMessage(six.with_metaclass(reflection.GeneratedProtocolMessageType, message.Message)):
      DESCRIPTOR = desc

    prius = CarMessage()
    prius.name = 'prius'
    prius.year = 2010
    prius.automatic = True
    prius.price = 25134.75
    prius.owners.extend(['bob', 'susan'])

    serialized_prius = prius.SerializeToString()
    new_prius = reflection.ParseMessage(desc, serialized_prius)
    self.assertTrue(new_prius is not prius)
    self.assertEqual(prius, new_prius)

    # these are unnecessary assuming message equality works as advertised but
    # explicitly check to be safe since we're mucking about in metaclass foo
    self.assertEqual(prius.name, new_prius.name)
    self.assertEqual(prius.year, new_prius.year)
    self.assertEqual(prius.automatic, new_prius.automatic)
    self.assertEqual(prius.price, new_prius.price)
    self.assertEqual(prius.owners, new_prius.owners)
项目:coremltools    作者:apple    | 项目源码 | 文件源码
def testDescriptorProtoSupport(self):
    # Hand written descriptors/reflection are only supported by the pure-Python
    # implementation of the API.
    if api_implementation.Type() != 'python':
      return

    def AddDescriptorField(proto, field_name, field_type):
      AddDescriptorField.field_index += 1
      new_field = proto.field.add()
      new_field.name = field_name
      new_field.type = field_type
      new_field.number = AddDescriptorField.field_index
      new_field.label = descriptor_pb2.FieldDescriptorProto.LABEL_OPTIONAL

    AddDescriptorField.field_index = 0

    desc_proto = descriptor_pb2.DescriptorProto()
    desc_proto.name = 'Car'
    fdp = descriptor_pb2.FieldDescriptorProto
    AddDescriptorField(desc_proto, 'name', fdp.TYPE_STRING)
    AddDescriptorField(desc_proto, 'year', fdp.TYPE_INT64)
    AddDescriptorField(desc_proto, 'automatic', fdp.TYPE_BOOL)
    AddDescriptorField(desc_proto, 'price', fdp.TYPE_DOUBLE)
    # Add a repeated field
    AddDescriptorField.field_index += 1
    new_field = desc_proto.field.add()
    new_field.name = 'owners'
    new_field.type = fdp.TYPE_STRING
    new_field.number = AddDescriptorField.field_index
    new_field.label = descriptor_pb2.FieldDescriptorProto.LABEL_REPEATED

    desc = descriptor.MakeDescriptor(desc_proto)
    self.assertTrue('name' in desc.fields_by_name)
    self.assertTrue('year' in desc.fields_by_name)
    self.assertTrue('automatic' in desc.fields_by_name)
    self.assertTrue('price' in desc.fields_by_name)
    self.assertTrue('owners' in desc.fields_by_name)

    class CarMessage(six.with_metaclass(reflection.GeneratedProtocolMessageType, message.Message)):
      DESCRIPTOR = desc

    prius = CarMessage()
    prius.name = 'prius'
    prius.year = 2010
    prius.automatic = True
    prius.price = 25134.75
    prius.owners.extend(['bob', 'susan'])

    serialized_prius = prius.SerializeToString()
    new_prius = reflection.ParseMessage(desc, serialized_prius)
    self.assertTrue(new_prius is not prius)
    self.assertEqual(prius, new_prius)

    # these are unnecessary assuming message equality works as advertised but
    # explicitly check to be safe since we're mucking about in metaclass foo
    self.assertEqual(prius.name, new_prius.name)
    self.assertEqual(prius.year, new_prius.year)
    self.assertEqual(prius.automatic, new_prius.automatic)
    self.assertEqual(prius.price, new_prius.price)
    self.assertEqual(prius.owners, new_prius.owners)
项目:go2mapillary    作者:enricofer    | 项目源码 | 文件源码
def testDescriptorProtoSupport(self):
    # Hand written descriptors/reflection are only supported by the pure-Python
    # implementation of the API.
    if api_implementation.Type() != 'python':
      return

    def AddDescriptorField(proto, field_name, field_type):
      AddDescriptorField.field_index += 1
      new_field = proto.field.add()
      new_field.name = field_name
      new_field.type = field_type
      new_field.number = AddDescriptorField.field_index
      new_field.label = descriptor_pb2.FieldDescriptorProto.LABEL_OPTIONAL

    AddDescriptorField.field_index = 0

    desc_proto = descriptor_pb2.DescriptorProto()
    desc_proto.name = 'Car'
    fdp = descriptor_pb2.FieldDescriptorProto
    AddDescriptorField(desc_proto, 'name', fdp.TYPE_STRING)
    AddDescriptorField(desc_proto, 'year', fdp.TYPE_INT64)
    AddDescriptorField(desc_proto, 'automatic', fdp.TYPE_BOOL)
    AddDescriptorField(desc_proto, 'price', fdp.TYPE_DOUBLE)
    # Add a repeated field
    AddDescriptorField.field_index += 1
    new_field = desc_proto.field.add()
    new_field.name = 'owners'
    new_field.type = fdp.TYPE_STRING
    new_field.number = AddDescriptorField.field_index
    new_field.label = descriptor_pb2.FieldDescriptorProto.LABEL_REPEATED

    desc = descriptor.MakeDescriptor(desc_proto)
    self.assertTrue('name' in desc.fields_by_name)
    self.assertTrue('year' in desc.fields_by_name)
    self.assertTrue('automatic' in desc.fields_by_name)
    self.assertTrue('price' in desc.fields_by_name)
    self.assertTrue('owners' in desc.fields_by_name)

    class CarMessage(six.with_metaclass(reflection.GeneratedProtocolMessageType, message.Message)):
      DESCRIPTOR = desc

    prius = CarMessage()
    prius.name = 'prius'
    prius.year = 2010
    prius.automatic = True
    prius.price = 25134.75
    prius.owners.extend(['bob', 'susan'])

    serialized_prius = prius.SerializeToString()
    new_prius = reflection.ParseMessage(desc, serialized_prius)
    self.assertTrue(new_prius is not prius)
    self.assertEqual(prius, new_prius)

    # these are unnecessary assuming message equality works as advertised but
    # explicitly check to be safe since we're mucking about in metaclass foo
    self.assertEqual(prius.name, new_prius.name)
    self.assertEqual(prius.year, new_prius.year)
    self.assertEqual(prius.automatic, new_prius.automatic)
    self.assertEqual(prius.price, new_prius.price)
    self.assertEqual(prius.owners, new_prius.owners)
项目:rpcDemo    作者:Tangxinwei    | 项目源码 | 文件源码
def testDescriptorProtoSupport(self):
    # Hand written descriptors/reflection are only supported by the pure-Python
    # implementation of the API.
    if api_implementation.Type() != 'python':
      return

    def AddDescriptorField(proto, field_name, field_type):
      AddDescriptorField.field_index += 1
      new_field = proto.field.add()
      new_field.name = field_name
      new_field.type = field_type
      new_field.number = AddDescriptorField.field_index
      new_field.label = descriptor_pb2.FieldDescriptorProto.LABEL_OPTIONAL

    AddDescriptorField.field_index = 0

    desc_proto = descriptor_pb2.DescriptorProto()
    desc_proto.name = 'Car'
    fdp = descriptor_pb2.FieldDescriptorProto
    AddDescriptorField(desc_proto, 'name', fdp.TYPE_STRING)
    AddDescriptorField(desc_proto, 'year', fdp.TYPE_INT64)
    AddDescriptorField(desc_proto, 'automatic', fdp.TYPE_BOOL)
    AddDescriptorField(desc_proto, 'price', fdp.TYPE_DOUBLE)
    # Add a repeated field
    AddDescriptorField.field_index += 1
    new_field = desc_proto.field.add()
    new_field.name = 'owners'
    new_field.type = fdp.TYPE_STRING
    new_field.number = AddDescriptorField.field_index
    new_field.label = descriptor_pb2.FieldDescriptorProto.LABEL_REPEATED

    desc = descriptor.MakeDescriptor(desc_proto)
    self.assertTrue('name' in desc.fields_by_name)
    self.assertTrue('year' in desc.fields_by_name)
    self.assertTrue('automatic' in desc.fields_by_name)
    self.assertTrue('price' in desc.fields_by_name)
    self.assertTrue('owners' in desc.fields_by_name)

    class CarMessage(six.with_metaclass(reflection.GeneratedProtocolMessageType, message.Message)):
      DESCRIPTOR = desc

    prius = CarMessage()
    prius.name = 'prius'
    prius.year = 2010
    prius.automatic = True
    prius.price = 25134.75
    prius.owners.extend(['bob', 'susan'])

    serialized_prius = prius.SerializeToString()
    new_prius = reflection.ParseMessage(desc, serialized_prius)
    self.assertTrue(new_prius is not prius)
    self.assertEqual(prius, new_prius)

    # these are unnecessary assuming message equality works as advertised but
    # explicitly check to be safe since we're mucking about in metaclass foo
    self.assertEqual(prius.name, new_prius.name)
    self.assertEqual(prius.year, new_prius.year)
    self.assertEqual(prius.automatic, new_prius.automatic)
    self.assertEqual(prius.price, new_prius.price)
    self.assertEqual(prius.owners, new_prius.owners)
项目:googleURLParser    作者:randomaccess3    | 项目源码 | 文件源码
def testDescriptorProtoSupport(self):
    # Hand written descriptors/reflection are only supported by the pure-Python
    # implementation of the API.
    if api_implementation.Type() != 'python':
      return

    def AddDescriptorField(proto, field_name, field_type):
      AddDescriptorField.field_index += 1
      new_field = proto.field.add()
      new_field.name = field_name
      new_field.type = field_type
      new_field.number = AddDescriptorField.field_index
      new_field.label = descriptor_pb2.FieldDescriptorProto.LABEL_OPTIONAL

    AddDescriptorField.field_index = 0

    desc_proto = descriptor_pb2.DescriptorProto()
    desc_proto.name = 'Car'
    fdp = descriptor_pb2.FieldDescriptorProto
    AddDescriptorField(desc_proto, 'name', fdp.TYPE_STRING)
    AddDescriptorField(desc_proto, 'year', fdp.TYPE_INT64)
    AddDescriptorField(desc_proto, 'automatic', fdp.TYPE_BOOL)
    AddDescriptorField(desc_proto, 'price', fdp.TYPE_DOUBLE)
    # Add a repeated field
    AddDescriptorField.field_index += 1
    new_field = desc_proto.field.add()
    new_field.name = 'owners'
    new_field.type = fdp.TYPE_STRING
    new_field.number = AddDescriptorField.field_index
    new_field.label = descriptor_pb2.FieldDescriptorProto.LABEL_REPEATED

    desc = descriptor.MakeDescriptor(desc_proto)
    self.assertTrue('name' in desc.fields_by_name)
    self.assertTrue('year' in desc.fields_by_name)
    self.assertTrue('automatic' in desc.fields_by_name)
    self.assertTrue('price' in desc.fields_by_name)
    self.assertTrue('owners' in desc.fields_by_name)

    class CarMessage(six.with_metaclass(reflection.GeneratedProtocolMessageType, message.Message)):
      DESCRIPTOR = desc

    prius = CarMessage()
    prius.name = 'prius'
    prius.year = 2010
    prius.automatic = True
    prius.price = 25134.75
    prius.owners.extend(['bob', 'susan'])

    serialized_prius = prius.SerializeToString()
    new_prius = reflection.ParseMessage(desc, serialized_prius)
    self.assertTrue(new_prius is not prius)
    self.assertEqual(prius, new_prius)

    # these are unnecessary assuming message equality works as advertised but
    # explicitly check to be safe since we're mucking about in metaclass foo
    self.assertEqual(prius.name, new_prius.name)
    self.assertEqual(prius.year, new_prius.year)
    self.assertEqual(prius.automatic, new_prius.automatic)
    self.assertEqual(prius.price, new_prius.price)
    self.assertEqual(prius.owners, new_prius.owners)