Python six.with_metaclass() Examples
The following are 30
code examples of six.with_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: reflection_test.py From go2mapillary with GNU General Public License v3.0 | 7 votes |
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])
Example #2
Source File: test_six.py From c4ddev with MIT License | 6 votes |
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)
Example #3
Source File: test_final.py From catalyst with Apache License 2.0 | 6 votes |
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
Example #4
Source File: test_final.py From zipline-chinese with Apache License 2.0 | 6 votes |
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')
Example #5
Source File: test_final.py From zipline-chinese with Apache License 2.0 | 6 votes |
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
Example #6
Source File: test_final.py From catalyst with Apache License 2.0 | 6 votes |
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')
Example #7
Source File: metautils.py From catalyst with Apache License 2.0 | 6 votes |
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)
Example #8
Source File: test_six.py From six with MIT License | 6 votes |
def test_with_metaclass_typing(): try: import typing except ImportError: pytest.skip("typing module required") class Meta(type): pass if sys.version_info[:2] < (3, 7): # Generics with custom metaclasses were broken on older versions. class Meta(Meta, typing.GenericMeta): pass T = typing.TypeVar('T') class G(six.with_metaclass(Meta, typing.Generic[T])): pass class GA(six.with_metaclass(abc.ABCMeta, typing.Generic[T])): pass assert isinstance(G, Meta) assert isinstance(GA, abc.ABCMeta) assert G[int] is not G[G[int]] assert GA[int] is not GA[GA[int]] assert G.__bases__ == (typing.Generic,) assert G.__orig_bases__ == (typing.Generic[T],)
Example #9
Source File: test_six.py From six with MIT License | 6 votes |
def test_with_metaclass_pep_560(): class Meta(type): pass class A: pass class B: pass class Fake: def __mro_entries__(self, bases): return (A, B) fake = Fake() class G(six.with_metaclass(Meta, fake)): pass class GA(six.with_metaclass(abc.ABCMeta, fake)): pass assert isinstance(G, Meta) assert isinstance(GA, abc.ABCMeta) assert G.__bases__ == (A, B) assert G.__orig_bases__ == (fake,)
Example #10
Source File: test_six.py From six with MIT License | 6 votes |
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)
Example #11
Source File: reflection_test.py From coremltools with BSD 3-Clause "New" or "Revised" License | 6 votes |
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])
Example #12
Source File: meta.py From chainer with MIT License | 6 votes |
def enable_final(base=(), meta_base=()): """Returns a base class in which ``final`` decorator is made available. Inheriting from the returned value of this function enables :meth:``~chainer.utils.final`` decorator to be applied to the methods of the class. Args: base (type or tuple of types): Base classes of the returned class. meta_base (type or tuples of type): Base metaclasses. If any descendant classes can directly or indirectly have any metaclasses, these metaclasses should be specified here to avoid the metaclass conflict. """ if not isinstance(base, (list, tuple)): base = (base,) if not isinstance(meta_base, (list, tuple)): meta_base = (meta_base,) base_metaclass = type('base_metaclass', (_EnableFinal,) + meta_base, {}) return six.with_metaclass(base_metaclass, *base)
Example #13
Source File: util_test.py From okcupyd with MIT License | 6 votes |
def test_decorate_all(): def add_two(function): def wrap(*args, **kwargs): return function(*args, **kwargs) + 2 return wrap class Test(six.with_metaclass(util.decorate_all(add_two))): def one(self): return 1 def two(self): return 2 assert Test().one() == 3 assert Test().two() == 4
Example #14
Source File: reflection_test.py From lambda-packs with MIT License | 6 votes |
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])
Example #15
Source File: reflection_test.py From keras-lambda with MIT License | 6 votes |
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])
Example #16
Source File: reflection_test.py From auto-alt-text-lambda-api with MIT License | 6 votes |
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])
Example #17
Source File: test_six.py From data with GNU General Public License v3.0 | 6 votes |
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)
Example #18
Source File: reflection_test.py From sklearn-theano with BSD 3-Clause "New" or "Revised" License | 6 votes |
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])
Example #19
Source File: test_six.py From data with GNU General Public License v3.0 | 6 votes |
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)
Example #20
Source File: reflection_test.py From Serverless-Deep-Learning-with-TensorFlow-and-AWS-Lambda with MIT License | 6 votes |
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])
Example #21
Source File: test_serializers.py From drf-haystack with MIT License | 5 votes |
def test_abstract_not_inherited(self): class Base(six.with_metaclass(HaystackSerializerMeta, serializers.Serializer)): _abstract = True def create_subclass(): class Sub(HaystackSerializer): pass self.assertRaises(ImproperlyConfigured, create_subclass)
Example #22
Source File: schema.py From flytekit with Apache License 2.0 | 5 votes |
def schema_instantiator_from_proto(schema_type): """ :param flytekit.models.types.SchemaType schema_type: :rtype: SchemaInstantiator """ class _Schema(_six.with_metaclass(SchemaInstantiator, Schema)): _schema_type = _schema_impl.SchemaType.promote_from_model(schema_type) return _Schema
Example #23
Source File: reflection_test.py From keras-lambda with MIT License | 5 votes |
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'))
Example #24
Source File: test_final.py From catalyst with Apache License 2.0 | 5 votes |
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)
Example #25
Source File: test_six.py From six with MIT License | 5 votes |
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)
Example #26
Source File: reflection_test.py From Serverless-Deep-Learning-with-TensorFlow-and-AWS-Lambda with MIT License | 5 votes |
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'))
Example #27
Source File: test_wargaming.py From python-wargaming with MIT License | 5 votes |
def get_demo_class(): class Demo(six.with_metaclass(MetaAPI, BaseAPI)): def __init__(self, *args, **kwargs): super(Demo, self).__init__(*args, **kwargs) self.sub_module_name.func3 = lambda: True return Demo
Example #28
Source File: test_wargaming.py From python-wargaming with MIT License | 5 votes |
def test_invalid_game(self): with self.assertRaises(ValidationError): class Demo(six.with_metaclass(MetaAPI, BaseAPI)): pass
Example #29
Source File: test_six.py From c4ddev with MIT License | 5 votes |
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)
Example #30
Source File: test_final.py From zipline-chinese with Apache License 2.0 | 5 votes |
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