python类ib()的实例源码

test_attrs.py 文件源码 项目:jsonschema-extractor 作者: toumorokoshi 项目源码 文件源码 阅读 14 收藏 0 点赞 0 评论 0
def test_unextractable_schema(extractor):
    """ test an attrs class which we can't extract schema from. """
    @attr.s
    class NoBueno(object):
        foo = attr.ib()
    with pytest.raises(UnextractableSchema):
        extractor.extract(NoBueno)
fields.py 文件源码 项目:reobject 作者: onyb 项目源码 文件源码 阅读 15 收藏 0 点赞 0 评论 0
def Field(*args, default=attr.NOTHING, **kwargs):
    if callable(default):
        default = attr.Factory(default)

    return attr.ib(*args, default=default, **kwargs)
fields.py 文件源码 项目:reobject 作者: onyb 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
def ForeignKey(cls, *args, **kwargs):
    metadata = {
        'related': {
            'target': cls,
            'type': 'ForeignKey',
        }
    }

    return attr.ib(*args, metadata=metadata, **kwargs)
replies.py 文件源码 项目:amqproto 作者: malinoff 项目源码 文件源码 阅读 15 收藏 0 点赞 0 评论 0
def __init_subclass__(cls, soft, reply_code, **kwargs):
        super().__init_subclass__(**kwargs)
        cls.soft = attr.ib(default=soft)
        cls.reply_code = attr.ib(default=reply_code)
        cls.BY_ID[reply_code] = cls
content.py 文件源码 项目:amqproto 作者: malinoff 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def __init_subclass__(cls, class_id, **kwargs):
        super().__init_subclass__(**kwargs)
        cls.class_id = attr.ib(default=class_id, init=False)
        cls.struct = make_struct(
            cls, exclude_attrs={'class_id'}, struct=PropertiesStruct
        )
        cls.BY_ID[class_id] = cls
utils.py 文件源码 项目:trip-based-public-transit-routing-algo 作者: mk-fg 项目源码 文件源码 阅读 16 收藏 0 点赞 0 评论 0
def attr_init(factory_or_default=attr.NOTHING, **attr_kws):
    if callable(factory_or_default): factory_or_default = attr.Factory(factory_or_default)
    return attr.ib(default=factory_or_default, **attr_kws)
attrs_extra.py 文件源码 项目:pillar 作者: armadillica 项目源码 文件源码 阅读 14 收藏 0 点赞 0 评论 0
def log(name):
    """Returns a logger attr.ib

    :param name: name to pass to logging.getLogger()
    :rtype: attr.ib
    """
    return attr.ib(default=logging.getLogger(name),
                   repr=False,
                   hash=False,
                   cmp=False)
base.py 文件源码 项目:niceman 作者: ReproNim 项目源码 文件源码 阅读 17 收藏 0 点赞 0 评论 0
def attrib(*args, **kwargs):
    """
    Extend the attr.ib to include our metadata elements.

    ATM we support additional keyword args which are then stored within
    `metadata`:
    - `doc` for documentation to describe the attribute (e.g. in --help)
    """
    doc = kwargs.pop('doc', None)
    metadata = kwargs.get('metadata', {})
    if doc:
        metadata['doc'] = doc
    if metadata:
        kwargs['metadata'] = metadata
    return attr.ib(*args, **kwargs)
vcs.py 文件源码 项目:niceman 作者: ReproNim 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def __init__(self, path, session):
        """Representation for a repository

        Parameters
        ----------
        path: str
           Path to the top of the repository

        """
        self.path = path.rstrip(os.sep)  # TODO: might be done as some rg to attr.ib
        self._session = session
        self._all_files = None
        self._branch = None
base.py 文件源码 项目:niceman 作者: ReproNim 项目源码 文件源码 阅读 16 收藏 0 点赞 0 评论 0
def TypedList(type_):
    """A helper to generate an attribute which would be with list factory 
    but also defining a type in its metadata
    """
    return attr.ib(default=Factory(list), metadata={'type': type_})


#
# Models
#
utils.py 文件源码 项目:pycoalaip 作者: bigchaindb 项目源码 文件源码 阅读 17 收藏 0 点赞 0 评论 0
def __setattr__(self, name, value):
        """Mimic attr.s(frozen=True) behaviour but allow for attributes
        to be initialized after class instantiation.

        Useful when you would like a class to be immutable after a
        certain action, such as a save to a database.

        Any attributes created with ``attr.ib(init=False)`` or are
        initially set to ``None`` in ``__init__()`` are allowed to have
        their values be set once after initialization. Any other
        attributes with initial values set are immediately frozen upon
        initialization.

        **Note**: Obviously, this doesn't stop anyone from setting the
        uninitialized attributes before you've set it yourself.
        Hopefully, you've got responsibile users.

        Raises:
            :class:`attr.exceptions.FronzenInstanceError`: if a frozen
                attribute is set
        """
        current_value = getattr(self, name, None)
        if current_value is None or isinstance(current_value, attr.Attribute):
            super().__setattr__(name, value)
        else:
            raise attr.exceptions.FrozenInstanceError()
test_model_validators.py 文件源码 项目:pycoalaip 作者: bigchaindb 项目源码 文件源码 阅读 15 收藏 0 点赞 0 评论 0
def test_is_callable_cls():
    from coalaip.model_validators import is_callable

    @attr.s
    class TestCallable:
        fn = attr.ib(validator=is_callable)

    return TestCallable
test_model_validators.py 文件源码 项目:pycoalaip 作者: bigchaindb 项目源码 文件源码 阅读 16 收藏 0 点赞 0 评论 0
def test_use_model_attr_cls():
    from coalaip.model_validators import use_model_attr

    @attr.s
    class TestUseModelAttr:
        validator = attr.ib()
        test = attr.ib(validator=use_model_attr('validator'))

    return TestUseModelAttr
test_model_validators.py 文件源码 项目:pycoalaip 作者: bigchaindb 项目源码 文件源码 阅读 15 收藏 0 点赞 0 评论 0
def create_test_does_not_contain_cls():
    from coalaip.model_validators import does_not_contain

    def create_cls(*avoid_keys):
        @does_not_contain(*avoid_keys)
        def validator(*args, **kwargs):
            pass

        @attr.s
        class TestDoesNotContain:
            data = attr.ib(validator=validator)

        return TestDoesNotContain

    return create_cls
test_authentication.py 文件源码 项目:txkube 作者: LeastAuthority 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def create_reactor():
    """
    Twisted 17.1.0 and higher requires a reactor which implements
    ``IReactorPluggableNameResolver``.
    """

    @implementer(IHostResolution)
    @attr.s
    class Resolution(object):
        name = attr.ib()

    class _FakeResolver(object):

        def resolveHostName(self, resolutionReceiver, hostName, *args,  **kwargs):
            portNumber = kwargs.pop('portNumber')
            r = Resolution(name=hostName)

            resolutionReceiver.resolutionBegan(r)
            if hostName in HOST_MAP:
                resolutionReceiver.addressResolved(
                    IPv4Address('TCP', HOST_MAP[hostName], portNumber))
            resolutionReceiver.resolutionComplete()
            return r

    @implementer(IReactorPluggableNameResolver)
    class _ResolvingMemoryClockReactor(MemoryReactorClock):
        nameResolver = _FakeResolver()

    return _ResolvingMemoryClockReactor()
test_hgvs_variantmapper_cp_altseqbuilder.py 文件源码 项目:hgvs 作者: biocommons 项目源码 文件源码 阅读 14 收藏 0 点赞 0 评论 0
def _run_comparison(self, hgvsc, expected_sequence):

        # test replicates the internal class of p_to_c
        @attr.s(slots=True)
        class RefTranscriptData(object):
            transcript_sequence = attr.ib()
            aa_sequence = attr.ib()
            cds_start = attr.ib()
            cds_stop = attr.ib()
            protein_accession = attr.ib()

            @classmethod
            def setup_transcript_data(cls, ac, ac_p, db, ref="GRCh37.p10"):
                """helper for generating RefTranscriptData from for c_to_p"""
                tx_info = db.get_tx_info(ac)
                tx_seq = db.get_tx_seq(ac)

                if tx_info is None or tx_seq is None:
                    raise hgvs.exceptions.HGVSError("Missing transcript data for accession: {}".format(ac))

                # use 1-based hgvs coords
                cds_start = tx_info["cds_start_i"] + 1
                cds_stop = tx_info["cds_end_i"]

                # padding list so biopython won't complain during the conversion
                tx_seq_to_translate = tx_seq[cds_start - 1:cds_stop]
                if len(tx_seq_to_translate) % 3 != 0:
                    "".join(list(tx_seq_to_translate).extend(["N"] * ((3 - len(tx_seq_to_translate) % 3) % 3)))

                tx_seq_cds = Seq(tx_seq_to_translate)
                protein_seq = str(tx_seq_cds.translate())

                transcript_data = RefTranscriptData(tx_seq, protein_seq, cds_start, cds_stop, ac_p)

                return transcript_data

        ac_p = "DUMMY"
        var = self._parser.parse_hgvs_variant(hgvsc)
        transcript_data = RefTranscriptData.setup_transcript_data(var.ac, ac_p, self._datasource)

        builder = altseqbuilder.AltSeqBuilder(var, transcript_data)
        insert_result = builder.build_altseq()
        actual_sequence = insert_result[0].transcript_sequence
        msg = "expected: {}\nactual  : {}".format(expected_sequence, actual_sequence)
        self.assertEqual(expected_sequence, actual_sequence, msg)
test_model.py 文件源码 项目:txkube 作者: LeastAuthority 项目源码 文件源码 阅读 33 收藏 0 点赞 0 评论 0
def test_comparison(self):
        """
        The binary comparison operations work on ``KubernetesError`` as expected.
        """
        model = v1_5_model

        a1 = KubernetesError(200, model.v1.Status(status=u"A"))
        a2 = KubernetesError(200, model.v1.Status(status=u"A"))
        b = KubernetesError(201, model.v1.Status(status=u"A"))
        c = KubernetesError(200, model.v1.Status(status=u"B"))

        # a1 == a2
        self.expectThat(a1, Equals(a2))
        # not (a1 != a2)
        self.expectThat(a1, Not(NotEquals(a2)))
        # not (a1 > a2)
        self.expectThat(a1, Not(GreaterThan(a2)))
        # not (a1 < a2)
        self.expectThat(a1, Not(LessThan(a2)))

        # not (a1 == b)
        self.expectThat(a1, Not(Equals(b)))
        # a1 != b
        self.expectThat(a1, NotEquals(b))
        # a1 < b
        self.expectThat(a1, LessThan(b))
        # not (a1 > b)
        self.expectThat(a1, Not(GreaterThan(b)))

        # not (a1 == c)
        self.expectThat(a1, Not(Equals(b)))
        # a1 != c
        self.expectThat(a1, NotEquals(b))
        # a1 < c
        self.expectThat(a1, LessThan(c))
        # not (a1 > c)
        self.expectThat(a1, Not(GreaterThan(c)))

        @attr.s
        class Comparator(object):
            result = attr.ib()

            def __cmp__(self, other):
                return self.result

        largest = Comparator(1)
        equalest = Comparator(0)
        smallest = Comparator(-1)

        # a1 < largest
        self.expectThat(a1, LessThan(largest))
        # a1 == equalest
        self.expectThat(a1, Equals(equalest))
        # a1 > smallest
        self.expectThat(a1, GreaterThan(smallest))


问题


面经


文章

微信
公众号

扫码关注公众号