• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python six.add_metaclass函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中six.add_metaclass函数的典型用法代码示例。如果您正苦于以下问题:Python add_metaclass函数的具体用法?Python add_metaclass怎么用?Python add_metaclass使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了add_metaclass函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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)
开发者ID:zamotivator,项目名称:seismograph,代码行数:9,代码来源:proxy.py


示例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
开发者ID:runt18,项目名称:pywikibot-core,代码行数:7,代码来源:utils.py


示例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
开发者ID:Annie201,项目名称:pywikibot-core,代码行数:7,代码来源:utils.py


示例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
开发者ID:AdamWill,项目名称:fedmsg,代码行数:7,代码来源:base.py


示例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]
开发者ID:LeotisBuchanan,项目名称:MySite,代码行数:8,代码来源:setup.py


示例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')
开发者ID:dx-entity,项目名称:env_controller,代码行数:54,代码来源:versionutils.py


示例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]
开发者ID:butterhirsch,项目名称:pyscaffold,代码行数:13,代码来源:utils.py


示例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")
开发者ID:Acidburn0zzz,项目名称:KomodoEdit,代码行数:56,代码来源:test_six.py


示例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
开发者ID:sarum90,项目名称:ziffect,代码行数:19,代码来源:__init__.py


示例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')
开发者ID:pizchen,项目名称:oslo.log,代码行数:38,代码来源:versionutils.py


示例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"])
开发者ID:duanshuaimin,项目名称:sentry,代码行数:30,代码来源:gzippeddict.py


示例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,
开发者ID:NuttasitBoonwat,项目名称:sentry,代码行数:29,代码来源:citext.py


示例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
开发者ID:skamithi,项目名称:pywikibot-core,代码行数:30,代码来源:aspects.py


示例14: reloadable_class

def reloadable_class(cls):
    """
    convinience decorator instead of @six.add_metaclass(ReloadingMetaclass)
    """
    return six.add_metaclass(ReloadingMetaclass)(cls)
开发者ID:Erotemic,项目名称:utool,代码行数:5,代码来源:util_class.py


示例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
开发者ID:Exal117,项目名称:pywikibot-core,代码行数:30,代码来源:script_tests.py


示例16: B

# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import six
six.add_metaclass(type)


ANSIBLE_METADATA = {'metadata_version': '1.1',
                    'status': ['preview'],
                    'supported_by': 'community'}

DOCUMENTATION = """
---
module: docker_facts
version_added: '2.6'
short_description: Gather list of volumes, images, containers
notes:
    - When specifying mulitple filters, only assets matching B(all) filters
      will be returned.
description:
开发者ID:openstack,项目名称:tripleo-validations,代码行数:31,代码来源:docker_facts.py


示例17: launch

        instance._launched = False
        instance.__init__()
        return instance

    def launch(self):
        """Start this component (but only do this once)"""
        if not self._launched:
            self._launched = True
            self.start()

    def start(self):
        """Start this component (top-level start does nothing)"""

    def stop(self):
        """Stop the component (top-level stop does nothing)"""
Component = six.add_metaclass(ComponentMeta)(Component)



class ComponentList(Component):
    """A list of components, used to implement dependency lists.

    This generally will not be instantiated by a user; instead,
    when a dependency is set to a list in the configuration,
    this is an adaptor to set that dependency to a list-like object
    with the ordered dependencies.

    """
    dependency_list = ListSetting()

    def __init__(self, components):
开发者ID:digidotcom,项目名称:epoxy,代码行数:31,代码来源:component.py


示例18: ROLLBACK_COMPLETE

class ROLLBACK_COMPLETE(Status): pass

class DELETE_IN_PROGRESS(Status): pass
class DELETE_FAILED(Status): pass
class DELETE_COMPLETE(Status): pass

class UPDATE_IN_PROGRESS(Status): pass
class UPDATE_COMPLETE_CLEANUP_IN_PROGRESS(Status): pass
class UPDATE_COMPLETE(Status): pass
class UPDATE_ROLLBACK_IN_PROGRESS(Status): pass
class UPDATE_ROLLBACK_FAILED(Status): pass
class UPDATE_ROLLBACK_COMPLETE_CLEANUP_IN_PROGRESS(Status): pass
class UPDATE_ROLLBACK_COMPLETE(Status): pass

for kls in [Status] + Status.__subclasses__():
    with_meta = six.add_metaclass(StatusMeta)(kls)
    locals()[kls.__name__] = with_meta
    Status.statuses[kls.__name__] = with_meta

class Cloudformation(AmazonMixin):
    def __init__(self, stack_name, region="ap-southeast-2"):
        self.region = region
        self.stack_name = stack_name

    @hp.memoized_property
    def conn(self):
        log.info("Using region [%s] for cloudformation (%s)", self.region, self.stack_name)
        return boto.cloudformation.connect_to_region(self.region)

    def reset(self):
        self._description = None
开发者ID:henrikhch,项目名称:bespin,代码行数:31,代码来源:cloudformation.py


示例19: TypeError

        else:
            raise TypeError("Expected an OID, got " + str(type(mech)))

        minor_status = ffi.new("OM_uint32[1]")
        out_name = ffi.new("gss_name_t[1]")
        try:
            retval = C.gss_canonicalize_name(minor_status, self._name[0], ffi.addressof(oid), out_name)
            if GSS_ERROR(retval):
                raise _exception_for_status(retval, minor_status[0])
            return MechName(out_name, mech)
        except:
            C.gss_release_name(minor_status, out_name)


# Add metaclass in Python 2/3 compatible way:
Name = six.add_metaclass(_NameMeta)(Name)


class MechName(Name):
    """
    Represents a GSSAPI Mechanism Name (MN) as obtained by
    :meth:`~gssapi.names.Name.canonicalize` or as the
    :attr:`~gssapi.ctx.AcceptContext.peer_name` property of an :class:`~gssapi.ctx.AcceptContext`.

    Don't construct instances of this class directly; use
    :meth:`~gssapi.names.Name.canonicalize` on a :class:`Name` to create a :class:`MechName`.
    """

    def __init__(self, name, mech_type):
        """Don't construct instances of this class directly; This object will acquire
        ownership of `name`, and release the associated storage when it is deleted."""
开发者ID:sigmaris,项目名称:python-gssapi,代码行数:31,代码来源:names.py


示例20: super

        value = super(EncryptedTextField, self).get_db_prep_value(value, *args, **kwargs)
        return encrypt(value)

    def to_python(self, value):
        if value is not None and isinstance(value, six.string_types):
            value = decrypt(value)
        return super(EncryptedTextField, self).to_python(value)

    def get_prep_lookup(self, lookup_type, value):
        raise NotImplementedError(
            '{!r} lookup type for {!r} is not supported'.format(
                lookup_type,
                self,
            )
        )


if hasattr(models, 'SubfieldBase'):
    EncryptedCharField = six.add_metaclass(models.SubfieldBase)(EncryptedCharField)
    EncryptedTextField = six.add_metaclass(models.SubfieldBase)(EncryptedTextField)

if 'south' in settings.INSTALLED_APPS:
    from south.modelsinspector import add_introspection_rules

    add_introspection_rules(
        [], ["^sentry\.db\.models\.fields\.encrypted\.EncryptedPickledObjectField"]
    )
    add_introspection_rules([], ["^sentry\.db\.models\.fields\.encrypted\.EncryptedCharField"])
    add_introspection_rules([], ["^sentry\.db\.models\.fields\.encrypted\.EncryptedJsonField"])
    add_introspection_rules([], ["^sentry\.db\.models\.fields\.encrypted\.EncryptedTextField"])
开发者ID:NuttasitBoonwat,项目名称:sentry,代码行数:30,代码来源:encrypted.py



注:本文中的six.add_metaclass函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python six.add_move函数代码示例发布时间:2022-05-27
下一篇:
Python shortcuts.get_object_or_none函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap