當前位置: 首頁>>代碼示例>>Python>>正文


Python dataclasses.asdict方法代碼示例

本文整理匯總了Python中dataclasses.asdict方法的典型用法代碼示例。如果您正苦於以下問題:Python dataclasses.asdict方法的具體用法?Python dataclasses.asdict怎麽用?Python dataclasses.asdict使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在dataclasses的用法示例。


在下文中一共展示了dataclasses.asdict方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: to_json

# 需要導入模塊: import dataclasses [as 別名]
# 或者: from dataclasses import asdict [as 別名]
def to_json(self) -> str:
        d = {k: v for k, v in dataclasses.asdict(self).items() if v}
        return json.dumps(d, ensure_ascii=False) 
開發者ID:wechatpy,項目名稱:wechatpy,代碼行數:5,代碼來源:schemes.py

示例2: test

# 需要導入模塊: import dataclasses [as 別名]
# 或者: from dataclasses import asdict [as 別名]
def test(self):
        # Given a completed scan for a server with the CERTIFICATE_INFO scan command
        server_location = ServerNetworkLocationViaDirectConnection.with_ip_address_lookup("www.facebook.com", 443)
        server_info = ServerConnectivityTester().perform(server_location)
        plugin_result = CertificateInfoImplementation.scan_server(server_info)
        scan_results = {ScanCommand.CERTIFICATE_INFO: plugin_result}
        scan_result = ServerScanResultFactory.create(scan_commands_results=scan_results)

        # When converting it into to JSON
        result_as_json = json.dumps(asdict(scan_result), cls=sslyze.JsonEncoder)

        # It succeeds
        assert result_as_json

        # And complex object like certificates were properly serialized
        assert "notBefore" in result_as_json
        assert "issuer" in result_as_json
        assert "subject" in result_as_json 
開發者ID:nabla-c0d3,項目名稱:sslyze,代碼行數:20,代碼來源:test_json.py

示例3: test_rsa_certificate

# 需要導入模塊: import dataclasses [as 別名]
# 或者: from dataclasses import asdict [as 別名]
def test_rsa_certificate(self):
        # Given a server that is configured with an RSA certificate
        with ModernOpenSslServer() as server:
            server_location = ServerNetworkLocationViaDirectConnection(
                hostname=server.hostname, port=server.port, ip_address=server.ip_address
            )
            server_info = ServerConnectivityTester().perform(server_location)

            # When running the scan, it succeeds
            scan_result = CertificateInfoImplementation.scan_server(server_info)
            assert scan_result.certificate_deployments[0].received_certificate_chain

            # And the result can be converted to JSON
            result_as_json = json.dumps(asdict(scan_result), cls=JsonEncoder)
            assert result_as_json

            # And the result can be converted to console output
            result_as_txt = CertificateInfoImplementation.cli_connector_cls.result_to_console_output(scan_result)
            assert result_as_txt 
開發者ID:nabla-c0d3,項目名稱:sslyze,代碼行數:21,代碼來源:test_certificate_algorithms.py

示例4: test_ed25519_certificate

# 需要導入模塊: import dataclasses [as 別名]
# 或者: from dataclasses import asdict [as 別名]
def test_ed25519_certificate(self):
        # Given a server that is configured with an ED25519 certificate
        with ModernOpenSslServer(
            server_certificate_path=Path(__file__).parent.absolute() / "server-ed25519-cert.pem",
            server_key_path=Path(__file__).parent.absolute() / "server-ed25519-key.pem",
        ) as server:
            server_location = ServerNetworkLocationViaDirectConnection(
                hostname=server.hostname, port=server.port, ip_address=server.ip_address
            )
            server_info = ServerConnectivityTester().perform(server_location)

            # When running the scan, it succeeds
            scan_result = CertificateInfoImplementation.scan_server(server_info)
            assert scan_result.certificate_deployments[0].received_certificate_chain

            # And the result can be converted to JSON
            result_as_json = json.dumps(asdict(scan_result), cls=JsonEncoder)
            assert result_as_json

            # And the result can be converted to console output
            result_as_txt = CertificateInfoImplementation.cli_connector_cls.result_to_console_output(scan_result)
            assert result_as_txt 
開發者ID:nabla-c0d3,項目名稱:sslyze,代碼行數:24,代碼來源:test_certificate_algorithms.py

示例5: set_config

# 需要導入模塊: import dataclasses [as 別名]
# 或者: from dataclasses import asdict [as 別名]
def set_config(js_context, config, intervention):
    """Set the non-state variables of the world3 simulator."""
    # Set global simulator parameters
    js_context.eval(f"startTime = {config.start_time}")
    js_context.eval(f"stopTime = {config.end_time}")
    js_context.eval(f"dt = {config.delta_t}")

    if intervention:
        intervention_config = config.update(intervention)
        js_context.eval(f"policyYear = {intervention.time}")
    else:
        intervention_config = config
        js_context.eval(f"policyYear = {config.end_time}")

    intervention_config = dataclasses.asdict(intervention_config)
    for parameter, before in dataclasses.asdict(config).items():
        if parameter in ["policy_year", "start_time", "end_time", "delta_t"]:
            continue
        after = intervention_config[parameter]
        js_context.eval(f"{to_camel_case(parameter)}.before = {before}")
        js_context.eval(f"{to_camel_case(parameter)}.after = {after}")
    js_context.eval("resetModel()") 
開發者ID:zykls,項目名稱:whynot,代碼行數:24,代碼來源:simulator.py

示例6: coerce_response

# 需要導入模塊: import dataclasses [as 別名]
# 或者: from dataclasses import asdict [as 別名]
def coerce_response(response_data):
    """Coerce response data to JSON serializable object with camelCase keys

    Recursively walk through the response object in case there are things
    like nested dataclasses that need to be reformatted

    :param response_data: data returned from the API request
    :returns: the same data but with keys in camelCase
    """
    if is_dataclass(response_data):
        coerced = {
            snake_to_camel(key): coerce_response(value)
            for key, value in asdict(response_data).items()
        }
    elif isinstance(response_data, dict):
        coerced = {
            snake_to_camel(key): coerce_response(value)
            for key, value in response_data.items()
        }
    elif isinstance(response_data, list):
        coerced = [coerce_response(item) for item in response_data]
    else:
        coerced = response_data

    return coerced 
開發者ID:MycroftAI,項目名稱:selene-backend,代碼行數:27,代碼來源:response.py

示例7: sync

# 需要導入模塊: import dataclasses [as 別名]
# 或者: from dataclasses import asdict [as 別名]
def sync(name, metrics):
    """Write markdown docs"""
    metrics_file = Path().resolve().parent / name / "metrics.yaml"
    cur = {}

    if metrics_file.exists():
        cur = yaml.round_trip_load(metrics_file.read_text())

    for m in metrics:
        entry = cur.setdefault(m.title, asdict(m))

        # If the fetched value exists override it, otherwise leave the current one alone.
        if m.description:
            entry["description"] = m.description
        if m.brief:
            entry["brief"] = m.brief
        if m.metric_type:
            entry["metric_type"] = m.metric_type

    with metrics_file.open("wt") as f:
        yaml.round_trip_dump(cur, f) 
開發者ID:signalfx,項目名稱:integrations,代碼行數:23,代碼來源:cloudsync.py

示例8: store

# 需要導入模塊: import dataclasses [as 別名]
# 或者: from dataclasses import asdict [as 別名]
def store(self, transitions: types.Transitions, truncate_ok: bool = True) -> None:
        """Store obs-act-obs triples.

        Args:
          transitions: Transitions to store.
          truncate_ok: If False, then error if the length of `transitions` is
            greater than `self.capacity`. Otherwise, store only the final
            `self.capacity` transitions.

        Raises:
            ValueError: The arguments didn't have the same length.
        """
        trans_dict = dataclasses.asdict(transitions)
        # Remove unnecessary fields
        trans_dict = {k: trans_dict[k] for k in self._buffer.sample_shapes.keys()}

        if len(transitions) > self.capacity and truncate_ok:
            trans_dict = {k: v[-self.capacity :] for k, v in trans_dict.items()}

        self._buffer.store(trans_dict) 
開發者ID:HumanCompatibleAI,項目名稱:imitation,代碼行數:22,代碼來源:buffer.py

示例9: __init__

# 需要導入模塊: import dataclasses [as 別名]
# 或者: from dataclasses import asdict [as 別名]
def __init__(
        self,
        transitions: types.Transitions,
        dict_dataset_cls: Type[DictDataset] = RandomDictDataset,
        dict_dataset_cls_kwargs: Optional[Mapping] = None,
    ):
        """Adapts a `DictDataset` class to build `Transitions` `Dataset`.

        Args:
            transitions: An `Transitions` instance to be sampled from and stored
                internally as a `dict` of copied arrays. Note that `sample` will return
                the same type of `Transitions` as the type of this arg. In other words,
                if `transitions` is an instance of `TransitionsWithRew`, then
                `.sample()` also returns `TransitionsWithRew`.
            dict_dataset_cls: `DictDataset` class to be adapted.
            dict_dataset_kwargs: Optional kwargs for initializing `DictDataset` class.
        """
        data_map: Dict[str, np.ndarray] = dataclasses.asdict(transitions)
        kwargs = dict_dataset_cls_kwargs or {}
        self.transitions_cls: Type[types.Transitions] = type(transitions)
        self.simple_dataset = dict_dataset_cls(
            data_map, **kwargs  # pytype: disable=not-instantiable
        ) 
開發者ID:HumanCompatibleAI,項目名稱:imitation,代碼行數:25,代碼來源:dataset.py

示例10: test_sample_sizes_and_types

# 需要導入模塊: import dataclasses [as 別名]
# 或者: from dataclasses import asdict [as 別名]
def test_sample_sizes_and_types(
        self,
        trans_ds,
        transitions,
        trans_ds_rew,
        transitions_rew,
        max_batch_size=50,
        n_checks=30,
    ):
        """Check for correct sample shapes and dtypes."""
        for ds, trans in [(trans_ds, transitions), (trans_ds_rew, transitions_rew)]:
            trans_dict = dataclasses.asdict(trans)
            for _ in range(n_checks):
                n_samples = np.random.randint(max_batch_size) + 1
                sample = ds.sample(n_samples)
                assert isinstance(sample, type(trans))
                for k, v in dataclasses.asdict(sample).items():
                    trans_v: np.ndarray = trans_dict[k]
                    assert v.dtype == trans_v.dtype
                    assert v.shape[1:] == trans_v.shape[1:]
                    assert v.shape[0] == n_samples 
開發者ID:HumanCompatibleAI,項目名稱:imitation,代碼行數:23,代碼來源:test_data.py

示例11: test_v23_bounds

# 需要導入模塊: import dataclasses [as 別名]
# 或者: from dataclasses import asdict [as 別名]
def test_v23_bounds():
    f = RelVolAdjFrameV23()
    adjustments = dataclasses.asdict(RelVolAdjFrameV23.VolumeAdjustments())

    for a in adjustments.keys():
        values = dict(adjustments)
        for value, raises in [
            (65537, True), (-65537, True),
            (65536, False), (-65536, False),
            (32769, False), (-32768, False),
            (777, False), (-999, False),
            (0, False), (-0, False),
        ]:
            values[a] = value
            if raises:
                with pytest.raises(ValueError):
                    f.adjustments = RelVolAdjFrameV23.VolumeAdjustments(**values)
                    f.render()
            else:
                f.adjustments = RelVolAdjFrameV23.VolumeAdjustments(**values)
                f.render()

        assert dataclasses.asdict(f.adjustments)[a] == value 
開發者ID:nicfit,項目名稱:eyeD3,代碼行數:25,代碼來源:test_rva.py

示例12: test_curve_parameters

# 需要導入模塊: import dataclasses [as 別名]
# 或者: from dataclasses import asdict [as 別名]
def test_curve_parameters(self):
        '''Test curve parameter.'''
        param = cli.Curve()
        self.assertRaises(click.BadParameter, param.convert,
                          value='', param=None, ctx=None)
        self.assertRaises(click.BadParameter, param.convert,
                          value='{}', param=None, ctx=None)
        missing_tau = '{"beta0": 0.017, "beta1": -0.023, "beta2": 0.24}'
        self.assertRaises(click.BadParameter, param.convert,
                          value=missing_tau, param=None, ctx=None)
        self.assertEqual(self.y1,
                         param.convert(json.dumps(asdict(self.y1)),
                                       None, None))
        self.assertEqual(self.y2,
                         param.convert(json.dumps(asdict(self.y2)),
                                       None, None)) 
開發者ID:luphord,項目名稱:nelson_siegel_svensson,代碼行數:18,代碼來源:test_nelson_siegel_svensson.py

示例13: test_metar_ete

# 需要導入模塊: import dataclasses [as 別名]
# 或者: from dataclasses import asdict [as 別名]
def test_metar_ete(self):
        """
        Performs an end-to-end test of all METAR JSON files
        """
        for ref, icao, issued in get_data(__file__, "metar"):
            station = metar.Metar(icao)
            raw = ref["data"]["raw"]
            self.assertEqual(station.sanitize(raw), ref["data"]["sanitized"])
            self.assertIsNone(station.last_updated)
            self.assertIsNone(station.issued)
            self.assertTrue(station.update(raw, issued=issued))
            self.assertIsInstance(station.last_updated, datetime)
            self.assertEqual(station.issued, issued)
            self.assertEqual(asdict(station.data), ref["data"])
            self.assertEqual(asdict(station.translations), ref["translations"])
            self.assertEqual(station.summary, ref["summary"])
            self.assertEqual(station.speech, ref["speech"]) 
開發者ID:avwx-rest,項目名稱:avwx-engine,代碼行數:19,代碼來源:test_metar.py

示例14: export_value

# 需要導入模塊: import dataclasses [as 別名]
# 或者: from dataclasses import asdict [as 別名]
def export_value(obj, key, value):
    # export and _asdict are not classmethods
    if hasattr(value, "ENTRY_POINT_ORIG_LABEL") and hasattr(value, "config"):
        obj[key] = {"plugin": value.ENTRY_POINT_ORIG_LABEL}
        export_value(obj[key], "config", value.config)
    elif inspect.isclass(value):
        obj[key] = value.__qualname__
    elif isinstance(value, (pathlib.Path, uuid.UUID)):
        obj[key] = str(value)
    elif hasattr(value, "export"):
        obj[key] = value.export()
    elif hasattr(value, "_asdict"):
        obj[key] = value._asdict()
    elif getattr(type(value), "__module__", None) == "numpy" and isinstance(
        getattr(value, "flatten", None), collections.Callable
    ):
        obj[key] = tuple(value.flatten())
    elif dataclasses.is_dataclass(value):
        obj[key] = export_dict(**dataclasses.asdict(value))
    elif getattr(value, "__module__", None) == "typing":
        obj[key] = STANDARD_TYPES.get(
            str(value).replace("typing.", ""), "generic"
        ) 
開發者ID:intel,項目名稱:dffml,代碼行數:25,代碼來源:data.py

示例15: to_dict

# 需要導入模塊: import dataclasses [as 別名]
# 或者: from dataclasses import asdict [as 別名]
def to_dict(self) -> Dict:
        return dataclasses.asdict(self) 
開發者ID:wechatpy,項目名稱:wechatpy,代碼行數:4,代碼來源:schemes.py


注:本文中的dataclasses.asdict方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。