How to use the six.add_metaclass function in six

To help you get started, we’ve selected a few six examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github sphinx-doc / sphinx / tests / roots / test-root / autodoc_target.py View on Github external
def __get__(self, obj, type=None):
        if obj is None:
            return self
        return 42

    def meth(self):
        """Function."""
        return "The Answer"


class CustomDataDescriptorMeta(type):
    """Descriptor metaclass docstring."""


@add_metaclass(CustomDataDescriptorMeta)
class CustomDataDescriptor2(CustomDataDescriptor):
    """Descriptor class with custom metaclass docstring."""


def _funky_classmethod(name, b, c, d, docstring=None):
    """Generates a classmethod for a class from a template by filling out
    some arguments."""
    def template(cls, a, b, c, d=4, e=5, f=6):
        return a, b, c, d, e, f
    from functools import partial
    function = partial(template, b=b, c=c, d=d)
    function.__name__ = name
    function.__doc__ = docstring
    return classmethod(function)
github google-research / task_adaptation / task_adaptation / data / data_testing_lib.py View on Github external
# See the License for the specific language governing permissions and
# limitations under the License.

"""Library for testing the dataset wrappers."""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import abc
import six
from task_adaptation.data import base
import tensorflow as tf


@six.add_metaclass(abc.ABCMeta)
class BaseDataTest(tf.test.TestCase):
  """Base class for testing subclasses of base.ImageData.

  To use this testing library, subclass BaseDataTest and override setUp().
  Pass into BaseDataTest's setUp method the expected statistics for the
  specific dataset being tested. These statistics are stored as instance
  attributes to be used in the tests.

  Attributes:
    data_wrapper: Subclass of base.ImageData for testing.
    default_label_key: str, key of the default output label tensor.
    expected_num_classes: Dict with the expected number of classes for each
      output label tensor.
    expected_num_samples: Dict containing expected number of examples in the
      "train", "val", "trainval", and "test" splits of the dataset.
    required_tensors_shapes: Dictionary with the names of the tensors that
github web-platform-tests / wpt / tools / six / test_six.py View on Github external
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")

    # Test a class with string for slots.
    class MyStringSlots(object):
        __slots__ = "ab"
    MyStringSlots = six.add_metaclass(Meta1)(MyStringSlots)
    assert MyStringSlots.__slots__ == "ab"
    instance = MyStringSlots()
    instance.ab = "foo"
    py.test.raises(AttributeError, setattr, instance, "a", "baz")
    py.test.raises(AttributeError, setattr, instance, "b", "baz")
github aws / aws-parallelcluster-node / src / common / schedulers / converters.py View on Github external
columns = lines[0].split(separator)
        rows = lines[1:]
        for row in rows:
            obj = obj_type()
            for item, column in zip(row.split(separator), columns):
                mapping = mappings.get(column)
                if mapping:
                    transformation_func = mapping.get("transformation")
                    value = item if transformation_func is None else transformation_func(item)
                    setattr(obj, mapping["field"], value)
            results.append(obj)

    return results


@add_metaclass(ABCMeta)
class ComparableObject:
    def __eq__(self, other):
        if type(other) is type(self):
            return self.__dict__ == other.__dict__
        return False

    def __ne__(self, other):
        return not self.__eq__(other)

    def __repr__(self):
        attrs = ", ".join(["{key}={value}".format(key=key, value=repr(value)) for key, value in self.__dict__.items()])
        return "{class_name}({attrs})".format(class_name=self.__class__.__name__, attrs=attrs)
github the-virtual-brain / tvb-framework / tvb / adapters / visualizers / surface_view.py View on Github external
# json_ui_filter = json.dumps([ui_filter.to_dict() for ui_filter in filters_ui])

        super(SurfaceViewerForm, self).__init__(prefix, project_id)
        self.surface = DataTypeSelectField(self.get_required_datatype(), self, name='surface',
                                           required=True, label='Brain surface')

    @staticmethod
    def get_required_datatype():
        return SurfaceIndex

    @staticmethod
    def get_input_name():
        return '_surface'


@add_metaclass(ABCMeta)
class ABCSurfaceDisplayer(ABCSpaceDisplayer):

    def generate_region_boundaries(self, surface_gid, region_mapping_gid):
        """
        Return the full region boundaries, including: vertices, normals and lines indices.
        """
        boundary_vertices = []
        boundary_lines = []
        boundary_normals = []

        surface_index = self.load_entity_by_gid(surface_gid)
        rm_index = self.load_entity_by_gid(region_mapping_gid)

        with h5.h5_file_for_index(rm_index) as rm_h5:
            array_data = rm_h5.array_data[:]
github lenarother / moderna / setup.py View on Github external
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]
github nokia / moler / moler / command.py View on Github external
"""

__author__ = 'Grzegorz Latuszek, Marcin Usielski, Michal Ernst'
__copyright__ = 'Copyright (C) 2018-2019, Nokia'
__email__ = 'grzegorz.latuszek@nokia.com, marcin.usielski@nokia.com, michal.ernst@nokia.com'

from abc import ABCMeta

from six import add_metaclass

from moler.connection_observer import ConnectionObserver
from moler.exceptions import NoCommandStringProvided
from moler.helpers import instance_id


@add_metaclass(ABCMeta)
class Command(ConnectionObserver):
    def __init__(self, connection=None, runner=None):
        """
        Create instance of Command class
        :param connection: connection used to start CMD and receive its output
        """
        super(Command, self).__init__(connection=connection, runner=runner)
        self.command_string = None
        self.cmd_name = Command.observer_name

    def __str__(self):
        cmd_str = self.command_string if self.command_string else ''
        if cmd_str[-1] == '\n':
            cmd_str = cmd_str[:-1] + r'<\n>'
        return '{}("{}", id:{})'.format(self.__class__.__name__, cmd_str, instance_id(self))
github trakt / Plex-Trakt-Scrobbler / Trakttv.bundle / Contents / Libraries / Linux / armv7_hf / marvell-pj4 / ucs4 / cryptography / hazmat / primitives / kdf / __init__.py View on Github external
# This file is dual licensed under the terms of the Apache License, Version
# 2.0, and the BSD License. See the LICENSE file in the root of this repository
# for complete details.

from __future__ import absolute_import, division, print_function

import abc

import six


@six.add_metaclass(abc.ABCMeta)
class KeyDerivationFunction(object):
    @abc.abstractmethod
    def derive(self, key_material):
        """
        Deterministically generates and returns a new key based on the existing
        key material.
        """

    @abc.abstractmethod
    def verify(self, key_material, expected_key):
        """
        Checks whether the key generated by the key material matches the
github roskakori / cutplace / setup.py View on Github external
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]
github openstack / nova / nova / compute / monitors / base.py View on Github external
#         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.

import abc

import six

from nova.objects import fields


@six.add_metaclass(abc.ABCMeta)
class MonitorBase(object):
    """Base class for all resource monitor plugins.

    A monitor is responsible for adding a set of related metrics to
    a `nova.objects.MonitorMetricList` object after the monitor has
    performed some sampling or monitoring action.
    """

    def __init__(self, compute_manager):
        self.compute_manager = compute_manager
        self.source = None

    @abc.abstractmethod
    def get_metric_names(self):
        """Get available metric names.