コード例 #1
0
 def _process_annotation(self, anno, flat=False):
     dflat = attrs.asdict(anno, filter=lambda a, v: v is not None)
     dflat = self._process_spatial(dflat)
     if flat:
         return dflat
     else:
         return self._unflatten_spatial_points(dflat)
コード例 #2
0
 def asdict(self) -> dict:
     """Return dictionary suitable for sending over CBOR."""
     d = asdict(self)
     d["test"] = d.pop("test_vectors")
     d["write"] = d.pop("write_vectors")
     d["new-length"] = d.pop("new_length")
     return d
コード例 #3
0
ファイル: test_next_gen.py プロジェクト: NI1993/attrs
    def test_smoke(self):
        """
        `attrs.asdict` only changes defaults, so we just call it and compare.
        """
        inst = C("foo", {(1, ): 42})

        assert attrs.asdict(inst) == _attr.asdict(inst,
                                                  retain_collection_types=True)
コード例 #4
0
    def _get_model_dict(self) -> dict:
        """Convenience method that wraps the `attrs.asdict` method. Returns the object's
        parameters as a dictionary.

        Returns
        -------
        dict
            The provided or default, if no input provided, model settings as a dictionary.
        """
        return attrs.asdict(self)
コード例 #5
0
ファイル: encoder.py プロジェクト: item4/yui
def encode(obj):
    if isinstance(obj, (list, tuple, set)):
        return [encode(x) for x in obj]
    elif issubclass(obj.__class__, enum.Enum):
        return obj.value
    elif isinstance(obj, dict):
        return {encode(k): encode(v) for k, v in obj.items() if v is not None}
    elif isinstance(obj, bool):
        return bool2str(obj)
    try:
        return encode(attrs.asdict(obj))
    except attrs.exceptions.NotAnAttrsClassError:
        pass
    return obj
コード例 #6
0
ファイル: endpoint.py プロジェクト: item4/yui
def prepare_for_json(obj):
    if isinstance(obj, (list, tuple, set)):
        return [prepare_for_json(x) for x in obj]
    elif issubclass(obj.__class__, enum.Enum):
        return obj.value
    elif isinstance(obj, dict):
        return {
            prepare_for_json(k): prepare_for_json(v)
            for k, v in obj.items() if v is not None and (
                (isinstance(v, list) and v) or not isinstance(v, list))
        }
    elif isinstance(obj, str):
        return obj
    try:
        return prepare_for_json(attrs.asdict(obj))
    except attrs.exceptions.NotAnAttrsClassError:
        pass
    return obj
コード例 #7
0
    async def read_test_write_chunks(
        self,
        storage_index: bytes,
        write_enabler_secret: bytes,
        lease_renew_secret: bytes,
        lease_cancel_secret: bytes,
        testwrite_vectors: dict[int, TestWriteVectors],
        read_vector: list[ReadVector],
    ) -> ReadTestWriteResult:
        """
        Read, test, and possibly write chunks to a particular mutable storage
        index.

        Reads are done before writes.

        Given a mapping between share numbers and test/write vectors, the tests
        are done and if they are valid the writes are done.
        """
        url = self._client.relative_url(
            "/v1/mutable/{}/read-test-write".format(_encode_si(storage_index)))
        message = {
            "test-write-vectors": {
                share_number: twv.asdict()
                for (share_number, twv) in testwrite_vectors.items()
            },
            "read-vector": [asdict(r) for r in read_vector],
        }
        response = await self._client.request(
            "POST",
            url,
            write_enabler_secret=write_enabler_secret,
            lease_renew_secret=lease_renew_secret,
            lease_cancel_secret=lease_cancel_secret,
            message_to_serialize=message,
        )
        if response.code == http.OK:
            result = await _decode_cbor(response,
                                        _SCHEMAS["mutable_read_test_write"])
            return ReadTestWriteResult(success=result["success"],
                                       reads=result["data"])
        else:
            raise ClientException(response.code, (await response.content()))
コード例 #8
0
attr.assoc(<warning descr="'attr.assoc' method should be called on attrs instances">B</warning>)
attr.evolve(<warning descr="'attr.evolve' method should be called on attrs instances">B</warning>)


@attrs.define
class B2:
    pass


attrs.fields(B2)
attrs.fields(<warning descr="'attr.fields' method should be called on attrs types">B2()</warning>)

attrs.fields_dict(B2)
attrs.fields_dict(<warning descr="'attr.fields_dict' method should be called on attrs types">B2()</warning>)

attrs.asdict(B2())
attrs.astuple(B2())
attrs.assoc(B2())
attrs.evolve(B2())

attrs.asdict(<warning descr="'attrs.asdict' method should be called on attrs instances">B2</warning>)
attrs.astuple(<warning descr="'attrs.astuple' method should be called on attrs instances">B2</warning>)
attrs.assoc(<warning descr="'attr.assoc' method should be called on attrs instances">B2</warning>)
attrs.evolve(<warning descr="'attr.evolve' method should be called on attrs instances">B2</warning>)


def unknown(p):
    attr.fields(p)
    attr.fields_dict(p)

    attr.asdict(p)
コード例 #9
0
ファイル: typing_example.py プロジェクト: NI1993/attrs
@attr.s
class FactoryTest:
    a: List[int] = attr.ib(default=attr.Factory(list))
    b: List[Any] = attr.ib(default=attr.Factory(list, False))
    c: List[int] = attr.ib(default=attr.Factory((lambda s: s.a), True))


@attrs.define
class FactoryTest2:
    a: List[int] = attrs.field(default=attrs.Factory(list))
    b: List[Any] = attrs.field(default=attrs.Factory(list, False))
    c: List[int] = attrs.field(default=attrs.Factory((lambda s: s.a), True))


attrs.asdict(FactoryTest2())
attr.asdict(FactoryTest(), tuple_keys=True)


# Check match_args stub
@attr.s(match_args=False)
class MatchArgs:
    a: int = attr.ib()
    b: int = attr.ib()


attr.asdict(FactoryTest())
attr.asdict(FactoryTest(), retain_collection_types=False)


# Check match_args stub
コード例 #10
0
def printjson(out: List[Role]):
    jsonpickle.set_encoder_options("json", ensure_ascii=False)
    print(jsonpickle.encode(asdict(Roles(out)), indent=4))
コード例 #11
0
ファイル: dataclass.py プロジェクト: XedaHQ/xeda
def asdict(inst: Any,
           filter_: Optional[Callable[..., bool]] = None) -> Dict[str, Any]:
    if isinstance(inst, BaseModel):
        assert filter_ is None
        return inst.dict()
    return attrs.asdict(inst, filter=filter_)