当前位置: 首页>>代码示例>>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;未经允许,请勿转载。