本文整理汇总了Python中six.add_metaclass函数的典型用法代码示例。如果您正苦于以下问题:Python add_metaclass函数的具体用法?Python add_metaclass怎么用?Python add_metaclass使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了add_metaclass函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: make_patch
def make_patch():
from selenium.webdriver.remote import webdriver
from selenium.webdriver.remote import webelement
webdriver.WebDriver = add_metaclass(ABCMeta)(webdriver.WebDriver)
webelement.WebElement = add_metaclass(ABCMeta)(webelement.WebElement)
webdriver.WebDriver.register(WebDriverProxy)
webelement.WebElement.register(WebElementProxy)
示例2: add_metaclass
def add_metaclass(cls):
"""Call six's add_metaclass with the site's __metaclass__ in Python 3."""
if not PY2:
return six.add_metaclass(cls.__metaclass__)(cls)
else:
assert cls.__metaclass__
return cls
示例3: add_metaclass
def add_metaclass(cls):
"""Call six's add_metaclass with the site's __metaclass__ in Python 3."""
if sys.version_info[0] > 2:
return six.add_metaclass(cls.__metaclass__)(cls)
else:
assert cls.__metaclass__
return cls
示例4: add_metaclass
def add_metaclass(metaclass):
""" Compat shim for el7. """
if hasattr(six, 'add_metaclass'):
return six.add_metaclass(metaclass)
else:
# Do nothing. It's not worth it.
return lambda klass: klass
示例5: capture_objs
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]
示例6: __call__
def __call__(self, func_or_cls):
report_deprecated = functools.partial(
deprecation_warning,
what=self.what or func_or_cls.__name__ + '()',
as_of=self.as_of,
in_favor_of=self.in_favor_of,
remove_in=self.remove_in)
if inspect.isfunction(func_or_cls):
@six.wraps(func_or_cls)
def wrapped(*args, **kwargs):
report_deprecated()
return func_or_cls(*args, **kwargs)
return wrapped
elif inspect.isclass(func_or_cls):
orig_init = func_or_cls.__init__
# TODO(tsufiev): change `functools` module to `six` as
# soon as six 1.7.4 (with fix for passing `assigned`
# argument to underlying `functools.wraps`) is released
# and added to the oslo-incubator requrements
@functools.wraps(orig_init, assigned=('__name__', '__doc__'))
def new_init(self, *args, **kwargs):
if self.__class__ in _DEPRECATED_EXCEPTIONS:
report_deprecated()
orig_init(self, *args, **kwargs)
func_or_cls.__init__ = new_init
_DEPRECATED_EXCEPTIONS.add(func_or_cls)
if issubclass(func_or_cls, Exception):
# NOTE(dhellmann): The subclasscheck is called,
# sometimes, to test whether a class matches the type
# being caught in an exception. This lets us warn
# folks that they are trying to catch an exception
# that has been deprecated. However, under Python 3
# the test for whether one class is a subclass of
# another has been optimized so that the abstract
# check is only invoked in some cases. (See
# PyObject_IsSubclass in cpython/Objects/abstract.c
# for the short-cut.)
class ExceptionMeta(type):
def __subclasscheck__(self, subclass):
if self in _DEPRECATED_EXCEPTIONS:
report_deprecated()
return super(ExceptionMeta,
self).__subclasscheck__(subclass)
func_or_cls = six.add_metaclass(ExceptionMeta)(func_or_cls)
_DEPRECATED_EXCEPTIONS.add(func_or_cls)
return func_or_cls
else:
raise TypeError('deprecated can be used only with functions or '
'classes')
示例7: capture_objs
def capture_objs(cls):
"""
Captures the instances of a given class during runtime
:param cls: class to capture
:return: dynamic list with references to all instances of ``cls``
"""
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]
示例8: test_add_metaclass
def test_add_metaclass():
class Meta(type):
pass
class X:
"success"
X = six.add_metaclass(Meta)(X)
assert type(X) is Meta
assert issubclass(X, object)
assert X.__module__ == __name__
assert X.__doc__ == "success"
class Base(object):
pass
class X(Base):
pass
X = six.add_metaclass(Meta)(X)
assert type(X) is Meta
assert issubclass(X, Base)
class Base2(object):
pass
class X(Base, Base2):
pass
X = six.add_metaclass(Meta)(X)
assert type(X) is Meta
assert issubclass(X, Base)
assert issubclass(X, Base2)
# Test a second-generation subclass of a type.
class Meta1(type):
m1 = "m1"
class Meta2(Meta1):
m2 = "m2"
class Base:
b = "b"
Base = six.add_metaclass(Meta1)(Base)
class X(Base):
x = "x"
X = six.add_metaclass(Meta2)(X)
assert type(X) is Meta2
assert issubclass(X, Base)
assert type(Base) is Meta1
assert "__dict__" not in vars(X)
instance = X()
instance.attr = "test"
assert vars(instance) == {"attr": "test"}
assert instance.b == Base.b
assert instance.x == X.x
# test a class with slots
class MySlots(object):
__slots__ = ["a", "b"]
MySlots = six.add_metaclass(Meta1)(MySlots)
assert MySlots.__slots__ == ["a", "b"]
instance = MySlots()
instance.a = "foo"
py.test.raises(AttributeError, setattr, instance, "c", "baz")
示例9: _make_intent_from_args
def _make_intent_from_args(args):
"""
Create an intent type for a given set of arguments.
:param args: a dict with keys as the names of arguments and values as
:class:`argument`s.
:returns: A new type that can hold all of the data to call a function that
has the given arguments.
"""
class _Intent(PClass):
pass
for name, arg in iteritems(args):
setattr(_Intent, name, field(type=arg.type))
_PIntent = add_metaclass(PClassMeta)(_Intent)
return _PIntent
示例10: __call__
def __call__(self, func_or_cls):
if not self.what:
self.what = func_or_cls.__name__ + '()'
msg, details = self._build_message()
if inspect.isfunction(func_or_cls):
@six.wraps(func_or_cls)
def wrapped(*args, **kwargs):
report_deprecated_feature(LOG, msg, details)
return func_or_cls(*args, **kwargs)
return wrapped
elif inspect.isclass(func_or_cls):
orig_init = func_or_cls.__init__
# TODO(tsufiev): change `functools` module to `six` as
# soon as six 1.7.4 (with fix for passing `assigned`
# argument to underlying `functools.wraps`) is released
# and added to the oslo-incubator requrements
@functools.wraps(orig_init, assigned=('__name__', '__doc__'))
def new_init(self, *args, **kwargs):
report_deprecated_feature(LOG, msg, details)
orig_init(self, *args, **kwargs)
func_or_cls.__init__ = new_init
if issubclass(func_or_cls, Exception):
class ExceptionMeta(type):
def __subclasscheck__(self, subclass):
if self in _DEPRECATED_EXCEPTIONS:
report_deprecated_feature(LOG, msg, details)
return super(ExceptionMeta,
self).__subclasscheck__(subclass)
func_or_cls = six.add_metaclass(ExceptionMeta)(func_or_cls)
_DEPRECATED_EXCEPTIONS.add(func_or_cls)
return func_or_cls
else:
raise TypeError('deprecated can be used only with functions or '
'classes')
示例11: get_prep_value
value = pickle.loads(decompress(value))
except Exception as e:
logger.exception(e)
return {}
elif not value:
return {}
return value
def get_prep_value(self, value):
if not value and self.null:
# save ourselves some storage
return None
# enforce six.text_type strings to guarantee consistency
if isinstance(value, six.binary_type):
value = six.text_type(value)
# db values need to be in unicode
return compress(pickle.dumps(value))
def value_to_string(self, obj):
value = self._get_val_from_obj(obj)
return self.get_prep_value(value)
if hasattr(models, 'SubfieldBase'):
GzippedDictField = six.add_metaclass(models.SubfieldBase)(GzippedDictField)
if 'south' in settings.INSTALLED_APPS:
from south.modelsinspector import add_introspection_rules
add_introspection_rules([], ["^sentry\.db\.models\.fields\.gzippeddict\.GzippedDictField"])
示例12: CITextField
class CITextField(CIText, models.TextField):
pass
class CICharField(CIText, models.CharField):
pass
class CIEmailField(CIText, models.EmailField):
pass
if hasattr(models, 'SubfieldBase'):
CITextField = six.add_metaclass(models.SubfieldBase)(CITextField)
CICharField = six.add_metaclass(models.SubfieldBase)(CICharField)
CIEmailField = six.add_metaclass(models.SubfieldBase)(CIEmailField)
if 'south' in settings.INSTALLED_APPS:
from south.modelsinspector import add_introspection_rules
add_introspection_rules([], ["^sentry\.db\.models\.fields\.citext\.CITextField"])
add_introspection_rules([], ["^sentry\.db\.models\.fields\.citext\.CICharField"])
add_introspection_rules([], ["^sentry\.db\.models\.fields\.citext\.CIEmailField"])
def create_citext_extension(db, **kwargs):
from sentry.utils.db import is_postgres
# We always need the citext extension installed for Postgres,
示例13: get_missing_article
def get_missing_article(self, site=None):
"""Get a Page which refers to a missing page on the site."""
if not site:
site = self.get_site()
page = pywikibot.Page(pywikibot.page.Link(
"There is no page with this title", site))
if page.exists():
raise unittest.SkipTest("Did not find a page that does not exist.")
return page
if sys.version_info[0] > 2:
import six
TestCase = six.add_metaclass(MetaTestCaseClass)(TestCase)
class DefaultSiteTestCase(TestCase):
"""Run tests against the config specified site."""
family = config.family
code = config.mylang
@classmethod
def override_default_site(cls, site):
print('%s using %s instead of %s:%s.'
% (cls.__name__, site, cls.family, cls.code))
cls.site = site
cls.family = site.family.name
示例14: reloadable_class
def reloadable_class(cls):
"""
convinience decorator instead of @six.add_metaclass(ReloadingMetaclass)
"""
return six.add_metaclass(ReloadingMetaclass)(cls)
示例15: setUp
depending on whether it is in the auto_run_script_list.
"""
__metaclass__ = TestScriptMeta
def setUp(self):
"""Prepare the environment for running the pwb.py script."""
super(TestScript, self).setUp()
self.old_pywikibot_dir = None
if 'PYWIKIBOT2_DIR' in os.environ:
self.old_pywikibot_dir = os.environ['PYWIKIBOT2_DIR']
os.environ['PYWIKIBOT2_DIR'] = pywikibot.config.base_dir
def tearDown(self):
"""Restore the environment after running the pwb.py script."""
super(TestScript, self).tearDown()
del os.environ['PYWIKIBOT2_DIR']
if self.old_pywikibot_dir:
os.environ['PYWIKIBOT2_DIR'] = self.old_pywikibot_dir
if sys.version_info[0] > 2:
import six
TestScript = six.add_metaclass(TestScriptMeta)(TestScript)
if __name__ == '__main__':
try:
unittest.main()
except SystemExit:
pass