本文整理汇总了Python中types.new_class函数的典型用法代码示例。如果您正苦于以下问题:Python new_class函数的具体用法?Python new_class怎么用?Python new_class使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了new_class函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _copy_module
def _copy_module(module, include=None, exclude=None):
copied = types.ModuleType(module.__name__)
copied.__package__ = getattr(module, "__package__", None)
for name, value in module.__dict__.items():
if (name.startswith("_") or (exclude is not None and name in exclude) or
(include is not None and name not in include)):
continue
type_ = type(value)
if value is None or type_ in (bool, bytes, float, int, str):
setattr(copied, name, value)
elif type_ in (types.FunctionType, types.LambdaType,
types.BuiltinFunctionType):
def func_proxy(func):
"""Return a proxy for the given function."""
# pylint: disable=unnecessary-lambda
return lambda *args, **kwargs: func(*args, **kwargs)
setattr(copied, name, func_proxy(value))
elif type_ is type and value is not type:
try:
proxy = types.new_class(name, bases=(value,))
proxy.mro = lambda: []
setattr(copied, name, types.new_class(name, bases=(proxy,)))
except TypeError:
pass
return copied
示例2: test_errors
def test_errors(self):
class MyMeta(type):
pass
with self.assertRaises(TypeError):
class MyClass(metaclass=MyMeta, otherarg=1):
pass
with self.assertRaises(TypeError):
types.new_class("MyClass", (object,),
dict(metaclass=MyMeta, otherarg=1))
types.prepare_class("MyClass", (object,),
dict(metaclass=MyMeta, otherarg=1))
class MyMeta(type):
def __init__(self, name, bases, namespace, otherarg):
super().__init__(name, bases, namespace)
with self.assertRaises(TypeError):
class MyClass(metaclass=MyMeta, otherarg=1):
pass
class MyMeta(type):
def __new__(cls, name, bases, namespace, otherarg):
return super().__new__(cls, name, bases, namespace)
def __init__(self, name, bases, namespace, otherarg):
super().__init__(name, bases, namespace)
self.otherarg = otherarg
class MyClass(metaclass=MyMeta, otherarg=1):
pass
self.assertEqual(MyClass.otherarg, 1)
示例3: test_both
def test_both(test_class, **kwargs):
frozen_tests = types.new_class('Frozen_'+test_class.__name__,
(test_class, unittest.TestCase))
source_tests = types.new_class('Source_'+test_class.__name__,
(test_class, unittest.TestCase))
frozen_tests.__module__ = source_tests.__module__ = test_class.__module__
for attr, (frozen_value, source_value) in kwargs.items():
setattr(frozen_tests, attr, frozen_value)
setattr(source_tests, attr, source_value)
return frozen_tests, source_tests
示例4: extension_add_event
def extension_add_event(self, code, evt, name = None):
"""extension_add_event(code, evt, [name])
Add an extension event. CODE is the numeric code, and EVT is
the event class. EVT will be cloned, and the attribute _code
of the new event class will be set to CODE.
If NAME is omitted, it will be set to the name of EVT. This
name is used to insert an entry in the DictWrapper
extension_event.
"""
if hasattr(types, 'ClassType'):
newevt = types.ClassType(evt.__name__, evt.__bases__,
evt.__dict__.copy())
else:
newevt = types.new_class(evt.__name__, evt.__bases__,
evt.__dict__.copy())
newevt._code = code
self.display.add_extension_event(code, newevt)
if name is None:
name = evt.__name__
setattr(self.extension_event, name, code)
示例5: extension_add_subevent
def extension_add_subevent(self, code, subcode, evt, name = None):
"""extension_add_subevent(code, evt, [name])
Add an extension subevent. CODE is the numeric code, subcode
is the sub-ID of this event that shares the code ID with other
sub-events and EVT is the event class. EVT will be cloned, and
the attribute _code of the new event class will be set to CODE.
If NAME is omitted, it will be set to the name of EVT. This
name is used to insert an entry in the DictWrapper
extension_event.
"""
if hasattr(types, 'ClassType'):
newevt = types.ClassType(evt.__name__, evt.__bases__,
evt.__dict__.copy())
else:
newevt = types.new_class(evt.__name__, evt.__bases__,
evt.__dict__.copy())
newevt._code = code
self.display.add_extension_event(code, newevt, subcode)
if name is None:
name = evt.__name__
# store subcodes as a tuple of (event code, subcode) in the
# extension dict maintained in the display object
setattr(self.extension_event, name, (code,subcode))
示例6: data_entry_form
def data_entry_form(self, row_name='new', data_instance = None, depth = 2):
self.form_class = None
self.classattr = {}
if data_instance is None:
data_instance = DataInstance(self.table_name, row_name, depth)
if row_name != 'new':
data_instance.get_linked_instances()
self.instance = data_instance
self.get_table(data_instance)
self.classattr['form_data_type_0'] = HiddenField('form_data_type_0', default=self.form_type)
self.classattr['form_data_table_0'] = HiddenField('form_data_table_0', default=self.table_name)
self.classattr['form_data_row_name_0'] = HiddenField('form_data_row_name_0', default=row_name)
self.classattr['row_counter'] = HiddenField('row_counter', default=data_instance.instance_counter)
form_class = new_class('SingleForm', (Form,), {}, lambda ns: ns.update(self.classattr))
logging.info(self.classattr)
logging.info(self.classattr)
self.form_class = form_class(None)
示例7: make_abc_subclasses
def make_abc_subclasses(base_class):
classes = []
for kind, abc in [('Frozen', frozen_abc), ('Source', source_abc)]:
name = '_'.join([kind, base_class.__name__])
base_classes = base_class, getattr(abc, base_class.__name__)
classes.append(types.new_class(name, base_classes))
return classes
示例8: test_metaclass_override_function
def test_metaclass_override_function(self):
# Special case: the given metaclass isn't a class,
# so there is no metaclass calculation.
class A(metaclass=self.Meta):
pass
marker = object()
def func(*args, **kwargs):
return marker
X = types.new_class("X", (), {"metaclass": func})
Y = types.new_class("Y", (object,), {"metaclass": func})
Z = types.new_class("Z", (A,), {"metaclass": func})
self.assertIs(marker, X)
self.assertIs(marker, Y)
self.assertIs(marker, Z)
示例9: ensure_tomes
def ensure_tomes(self):
for number in range(1, 29):
class_id = 'Tome_{0:02d}'.format(number)
self.tomes[number] = types.new_class(
correct_owl_id(class_id),
(Tome, ),
kwds = { "ontology" : onto }
)
示例10: test_new_class_metaclass_keywords
def test_new_class_metaclass_keywords(self):
#Test that keywords are passed to the metaclass:
def meta_func(name, bases, ns, **kw):
return name, bases, ns, kw
res = types.new_class("X",
(int, object),
dict(metaclass=meta_func, x=0))
self.assertEqual(res, ("X", (int, object), {}, {"x": 0}))
示例11: test_new_class_meta
def test_new_class_meta(self):
Meta = self.Meta
settings = {"metaclass": Meta, "z": 2}
# We do this twice to make sure the passed in dict isn't mutated
for i in range(2):
C = types.new_class("C" + str(i), (), settings)
self.assertIsInstance(C, Meta)
self.assertEqual(C.y, 1)
self.assertEqual(C.z, 2)
示例12: decorator
def decorator(cls):
assert isinstance(driver, Driver)
assert issubclass(cls, Schema)
assert not issubclass(cls, DrivedMixin)
drived_class = new_class(cls.__name__, (cls, DrivedMixin))
drived_class.driver = driver
return drived_class
示例13: test_new_class_exec_body
def test_new_class_exec_body(self):
Meta = self.Meta
def func(ns):
ns["x"] = 0
C = types.new_class("C", (), {"metaclass": Meta, "z": 2}, func)
self.assertIsInstance(C, Meta)
self.assertEqual(C.x, 0)
self.assertEqual(C.y, 1)
self.assertEqual(C.z, 2)
示例14: test_prepare_class
def test_prepare_class(self):
# Basic test of metaclass derivation
expected_ns = {}
class A(type):
def __new__(*args, **kwargs):
return type.__new__(*args, **kwargs)
def __prepare__(*args):
return expected_ns
B = types.new_class("B", (object,))
C = types.new_class("C", (object,), {"metaclass": A})
# The most derived metaclass of D is A rather than type.
meta, ns, kwds = types.prepare_class("D", (B, C), {"metaclass": type})
self.assertIs(meta, A)
self.assertIs(ns, expected_ns)
self.assertEqual(len(kwds), 0)
示例15: make_return_value_tests
def make_return_value_tests(base_class, test_class):
frozen_class, source_class = make_abc_subclasses(base_class)
tests = []
for prefix, class_in_test in [('Frozen', frozen_class), ('Source', source_class)]:
def set_ns(ns):
ns['ins'] = class_in_test()
tests.append(types.new_class('_'.join([prefix, test_class.__name__]),
(test_class, unittest.TestCase),
exec_body=set_ns))
return tests