Python attr.asdict() Examples

The following are 30 code examples of attr.asdict(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module attr , or try the search function .
Example #1
Source File: computation_types.py    From federated with Apache License 2.0 6 votes vote down vote up
def _to_type_from_attrs(spec) -> Type:
  """Converts an `attr.s` class or instance to a `tff.Type`."""
  if isinstance(spec, type):
    # attrs class type, introspect the attributes for their type annotations.
    elements = [(a.name, a.type) for a in attr.fields(spec)]
    missing_types = [n for (n, t) in elements if not t]
    if missing_types:
      raise TypeError((
          "Cannot infer tff.Type for attr.s class '{}' because some attributes "
          'were missing type specifications: {}').format(
              spec.__name__, missing_types))
    the_type = spec
  else:
    # attrs class instance, inspect the field values for instances convertible
    # to types.
    elements = attr.asdict(
        spec, dict_factory=collections.OrderedDict, recurse=False)
    the_type = type(spec)

  return NamedTupleTypeWithPyContainerType(elements, the_type) 
Example #2
Source File: version.py    From renku-python with Apache License 2.0 6 votes vote down vote up
def dump(self, app_name):
        """Store information in a cache."""
        cache = self._cache(app_name)

        # Attempt to write out our version check file
        with lockfile.LockFile(str(cache)):
            if cache.exists():
                with cache.open() as fp:
                    state = json.load(fp)
            else:
                state = {}

            state[sys.prefix] = attr.asdict(self)

            with cache.open('w') as fp:
                json.dump(state, fp, sort_keys=True) 
Example #3
Source File: test_tables.py    From tskit with MIT License 6 votes vote down vote up
def test_asdict(self):
        ts = msprime.simulate(10, mutation_rate=1, random_seed=1)
        t = ts.tables
        self.add_metadata(t)
        d1 = {
            "encoding_version": (1, 1),
            "sequence_length": t.sequence_length,
            "metadata_schema": str(t.metadata_schema),
            "metadata": t.metadata_schema.encode_row(t.metadata),
            "individuals": t.individuals.asdict(),
            "populations": t.populations.asdict(),
            "nodes": t.nodes.asdict(),
            "edges": t.edges.asdict(),
            "sites": t.sites.asdict(),
            "mutations": t.mutations.asdict(),
            "migrations": t.migrations.asdict(),
            "provenances": t.provenances.asdict(),
        }
        d2 = t.asdict()
        self.assertEqual(set(d1.keys()), set(d2.keys()))
        t1 = tskit.TableCollection.fromdict(d1)
        t2 = tskit.TableCollection.fromdict(d2)
        self.assertEqual(t1, t2) 
Example #4
Source File: test_tables.py    From tskit with MIT License 6 votes vote down vote up
def test_from_dict(self):
        ts = msprime.simulate(10, mutation_rate=1, random_seed=1)
        t1 = ts.tables
        self.add_metadata(t1)
        d = {
            "encoding_version": (1, 1),
            "sequence_length": t1.sequence_length,
            "metadata_schema": str(t1.metadata_schema),
            "metadata": t1.metadata_schema.encode_row(t1.metadata),
            "individuals": t1.individuals.asdict(),
            "populations": t1.populations.asdict(),
            "nodes": t1.nodes.asdict(),
            "edges": t1.edges.asdict(),
            "sites": t1.sites.asdict(),
            "mutations": t1.mutations.asdict(),
            "migrations": t1.migrations.asdict(),
            "provenances": t1.provenances.asdict(),
        }
        t2 = tskit.TableCollection.fromdict(d)
        self.assertEquals(t1, t2) 
Example #5
Source File: test_all.py    From dephell with MIT License 6 votes vote down vote up
def test_repository_preserve(converter):
    repo = RepositoriesRegistry()
    repo.add_repo(url='https://example.com', name='insane')
    repo.add_repo(url='https://pypi.org/simple/', name='pypi')
    root = RootDependency()
    dep1 = DependencyMaker.from_params(
        source=root,
        raw_name='dephell',
        constraint='*',
        repo=repo,
    )[0]
    req = Requirement(dep=dep1, roots=[root.name], lock=False)

    content1 = converter.dumps([req], project=root)
    root2 = converter.loads(content1)
    assert len(root2.dependencies) == 1
    dep2 = root2.dependencies[0]

    repos1 = [attr.asdict(repo) for repo in dep1.repo.repos]
    repos2 = [attr.asdict(repo) for repo in dep2.repo.repos]
    assert repos1 == repos2 
Example #6
Source File: worker.py    From trains-agent with Apache License 2.0 6 votes vote down vote up
def get_execution_info(self, current_task):
        # type: (...) -> ExecutionInfo
        try:
            execution = ExecutionInfo.from_task(current_task)
        except Exception as e:
            self.error("Could not parse task execution info: {}".format(e.args[0]))
            current_task.failed(
                status_reason=e.args[0], status_message=self._task_status_change_message
            )
            self.exit(e.args[0])
        if "\\" in execution.working_dir:
            warning(
                'Working dir "{}" contains backslashes. '
                "All path separators must be forward slashes.".format(
                    execution.working_dir
                )
            )
        print("Executing task id [%s]:" % current_task.id)
        for pair in attr.asdict(execution).items():
            print("{} = {}".format(*pair))
        print()
        return execution 
Example #7
Source File: endpoint.py    From yui with GNU Affero General Public License v3.0 6 votes vote down vote up
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(attr.asdict(obj))
    except attr.exceptions.NotAnAttrsClassError:
        pass
    return obj 
Example #8
Source File: main.py    From python-songpal with GNU General Public License v3.0 6 votes vote down vote up
def dump_devinfo(dev: Device, file):
    """Dump developer information.

    Pass `file` to write the results directly into a file.
    """
    import attr

    methods = await dev.get_supported_methods()
    res = {
        "supported_methods": {k: v.asdict() for k, v in methods.items()},
        "settings": [attr.asdict(x) for x in await dev.get_settings()],
        "sysinfo": attr.asdict(await dev.get_system_info()),
        "interface_info": attr.asdict(await dev.get_interface_information()),
    }
    if file:
        click.echo("Saving to file: %s" % file.name)
        json.dump(res, file, sort_keys=True, indent=4)
    else:
        click.echo(json.dumps(res, sort_keys=True, indent=4)) 
Example #9
Source File: metadata.py    From aws-encryption-sdk-cli with Apache License 2.0 6 votes vote down vote up
def json_ready_header_auth(header_auth):
    # type: (MessageHeaderAuthentication) -> Dict[str, Text]
    """Create a JSON-serializable representation of a
    :class:`aws_encryption_sdk.internal.structures.MessageHeaderAuthentication`.

    http://docs.aws.amazon.com/encryption-sdk/latest/developer-guide/message-format.html#header-authentication

    :param header_auth: header auth for which to create a JSON-serializable representation
    :type header_auth: aws_encryption_sdk.internal.structures.MessageHeaderAuthentication
    :rtype: dict
    """
    dict_header_auth = attr.asdict(header_auth)

    for key, value in dict_header_auth.items():
        dict_header_auth[key] = unicode_b64_encode(value)

    return dict_header_auth 
Example #10
Source File: error_metrics.py    From ml-fairness-gym with Apache License 2.0 5 votes vote down vote up
def to_jsonable(self):
    return {'___CONFUSION_MATRIX___': attr.asdict(self)} 
Example #11
Source File: worker.py    From trains-agent with Apache License 2.0 5 votes vote down vote up
def get_repo_info(self, execution, task, venv_folder):
        # type: (ExecutionInfo, tasks_api.Task, str) -> Tuple[str, Optional[VCS], Optional[RepoInfo]]
        literal_script = LiteralScriptManager(venv_folder)
        has_repository = bool(execution.repository)
        is_literal_script = literal_script.is_literal_script(task)
        if not has_repository and not is_literal_script:
            raise CommandFailedError(
                "Can not run task without repository or literal script in `script.diff`"
            )
        repo_info = None
        directory = None
        vcs = None
        if has_repository:
            vcs, repo_info = self._get_repo_info(execution, task, venv_folder)
            directory = Path(repo_info.root, execution.working_dir or ".")

            for pair in attr.asdict(repo_info).items():
                print("{}: {}".format(*pair))
            if not is_literal_script:
                self.apply_diff(
                    task=task, vcs=vcs, execution_info=execution, repo_info=repo_info
                )
        if is_literal_script:
            self.log.info("found literal script in `script.diff`")
            directory, script = literal_script.create_notebook_file(
                task, execution, repo_info
            )
            execution.entry_point = script
            if not has_repository:
                return directory, None, None
        else:
            # in case of no literal script, there is not difference between empty working dir and `.`
            execution.working_dir = execution.working_dir or "."
        if not directory:
            assert False, "unreachable code"
        return directory, vcs, repo_info 
Example #12
Source File: restaurant_toy_recsim.py    From ml-fairness-gym with Apache License 2.0 5 votes vote down vote up
def to_jsonable(self):
    return attr.asdict(self) 
Example #13
Source File: restaurant_toy_recsim.py    From ml-fairness-gym with Apache License 2.0 5 votes vote down vote up
def build_user_components(config):
  """Returns the user components of the simulator."""
  user_constuctor = functools.partial(User, **attr.asdict(config.user_config))
  user_sampler = recsim_samplers.ConstructionSampler(user_constuctor,
                                                     config.seeds.user_sampler)
  user_model = UserModel(
      user_sampler=user_sampler, seed=config.seeds.user_model)
  return user_sampler, user_model 
Example #14
Source File: movie_lens_dynamic_test.py    From ml-fairness-gym with Apache License 2.0 5 votes vote down vote up
def _initialize_from_config(self, env_config):
    self.working_dir = tempfile.mkdtemp(dir=FLAGS.test_tmpdir)

    self.initial_embeddings = movie_lens_utils.load_embeddings(env_config)

    user_ctor = functools.partial(movie_lens.User,
                                  **attr.asdict(env_config.user_config))
    self.dataset = movie_lens_utils.Dataset(
        env_config.data_dir,
        user_ctor=user_ctor,
        movie_ctor=movie_lens.Movie,
        embeddings=self.initial_embeddings)

    self.document_sampler = recsim_samplers.SingletonSampler(
        self.dataset.get_movies(), movie_lens.Movie)

    self.user_sampler = recsim_samplers.UserPoolSampler(
        seed=env_config.seeds.user_sampler,
        users=self.dataset.get_users(),
        user_ctor=user_ctor)

    self.user_model = movie_lens.UserModel(
        user_sampler=self.user_sampler,
        seed=env_config.seeds.user_model,
    )

    env = movie_lens.MovieLensEnvironment(
        self.user_model,
        self.document_sampler,
        num_candidates=self.document_sampler.size(),
        slate_size=1,
        resample_documents=False)
    env.reset()

    reward_aggregator = functools.partial(
        movie_lens.multiobjective_reward,
        lambda_non_violent=env_config.lambda_non_violent)
    self.env = recsim_gym.RecSimGymEnv(env, reward_aggregator) 
Example #15
Source File: pairwise_distance.py    From neural-structured-learning with Apache License 2.0 5 votes vote down vote up
def get_config(self):
    distance_config = attr.asdict(self._distance_config)
    distance_config.update({
        k: v.value
        for k, v in distance_config.items()
        if isinstance(v, enum.Enum)
    })
    config = super(PairwiseDistance, self).get_config()
    config["distance_config"] = distance_config
    return config 
Example #16
Source File: solve_poly.py    From coveragepy with Apache License 2.0 5 votes vote down vote up
def calc_total_error(inputs_outputs, coefficients, name):
    total_error = 0
    for inputs, outputs in inputs_outputs.items():
        total_error += abs(calc_error(attr.asdict(inputs), attr.asdict(outputs)[name], coefficients))

    return total_error 
Example #17
Source File: conf.py    From stmocli with Mozilla Public License 2.0 5 votes vote down vote up
def to_dict(self):
        return attr.asdict(self) 
Example #18
Source File: test_tables.py    From tskit with MIT License 5 votes vote down vote up
def test_roundtrip_dict(self):
        ts = msprime.simulate(10, mutation_rate=1, random_seed=1)
        t1 = ts.tables
        t2 = tskit.TableCollection.fromdict(t1.asdict())
        self.assertEqual(t1, t2)

        self.add_metadata(t1)
        t2 = tskit.TableCollection.fromdict(t1.asdict())
        self.assertEqual(t1, t2) 
Example #19
Source File: metadata.py    From aws-encryption-sdk-cli with Apache License 2.0 5 votes vote down vote up
def json_ready_header(header):
    # type: (MessageHeader) -> Dict[str, Any]
    """Create a JSON-serializable representation of a :class:`aws_encryption_sdk.structures.MessageHeader`.

    http://docs.aws.amazon.com/encryption-sdk/latest/developer-guide/message-format.html#header-structure

    :param header: header for which to create a JSON-serializable representation
    :type header: aws_encryption_sdk.structures.MessageHeader
    :rtype: dict
    """
    dict_header = attr.asdict(header)

    del dict_header["content_aad_length"]
    dict_header["version"] = str(float(dict_header["version"].value))
    dict_header["algorithm"] = dict_header["algorithm"].name

    for key, value in dict_header.items():
        if isinstance(value, Enum):
            dict_header[key] = value.value

    dict_header["message_id"] = unicode_b64_encode(dict_header["message_id"])

    dict_header["encrypted_data_keys"] = sorted(
        list(dict_header["encrypted_data_keys"]),
        key=lambda x: six.b(x["key_provider"]["provider_id"]) + x["key_provider"]["key_info"],
    )
    for data_key in dict_header["encrypted_data_keys"]:
        data_key["key_provider"]["provider_id"] = unicode_b64_encode(six.b(data_key["key_provider"]["provider_id"]))
        data_key["key_provider"]["key_info"] = unicode_b64_encode(data_key["key_provider"]["key_info"])
        data_key["encrypted_data_key"] = unicode_b64_encode(data_key["encrypted_data_key"])

    return dict_header 
Example #20
Source File: puppet.py    From mautrix-facebook with GNU Affero General Public License v3.0 5 votes vote down vote up
def _get_displayname(cls, info: fbchat.UserData) -> str:
        displayname = None
        for preference in config["bridge.displayname_preference"]:
            if getattr(info, preference, None):
                displayname = getattr(info, preference)
        return config["bridge.displayname_template"].format(displayname=displayname,
                                                            **attr.asdict(info)) 
Example #21
Source File: public.py    From mautrix-facebook with GNU Affero General Public License v3.0 5 votes vote down vote up
def status(self, request: web.Request) -> web.Response:
        user = self.check_token(request)
        data = {
            "permissions": user.permission_level,
            "mxid": user.mxid,
            "user_agent": user.user_agent,
            "facebook": None,
        }
        if await user.is_logged_in():
            info = cast(fbchat.UserData, await user.client.fetch_thread_info([user.fbid]).__anext__())
            data["facebook"] = attr.asdict(info)
            del data["facebook"]["session"]
        return web.json_response(data, headers=self._acao_headers) 
Example #22
Source File: solve_poly.py    From coveragepy-bbmirror with Apache License 2.0 5 votes vote down vote up
def calc_total_error(inputs_outputs, coefficients, name):
    total_error = 0
    for inputs, outputs in inputs_outputs.items():
        total_error += abs(calc_error(attr.asdict(inputs), attr.asdict(outputs)[name], coefficients))

    return total_error 
Example #23
Source File: pdf_chapter_diff.py    From OpenXR-SDK-Source with Apache License 2.0 5 votes vote down vote up
def asdict(self):
        return attr.asdict(self,
                           filter=attr.filters.exclude(
                               attr.fields(Section).pdf)) 
Example #24
Source File: pdf_chapter_diff.py    From OpenXR-SDK-Source with Apache License 2.0 5 votes vote down vote up
def pdf_diff_options(self):
        fields = attr.fields(Section)
        ret = attr.asdict(self, filter=attr.filters.include(
            fields.page_start, fields.page_end))
        ret['fn'] = str(self.pdf.fn)
        if self.page_start_top:
            ret['page_start_top'] = self.page_start_top

        if self.page_end_bottom:
            ret['page_end_bottom'] = self.page_end_bottom
        return ret 
Example #25
Source File: pdf_chapter_diff.py    From OpenXR-SDK-Source with Apache License 2.0 5 votes vote down vote up
def asdict(self):
        # fields = attr.fields(Section)
        return attr.asdict(self) 
Example #26
Source File: test_middleware.py    From scrapy-poet with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def to_item(self):
        return attr.asdict(self, recurse=False) 
Example #27
Source File: test_middleware.py    From scrapy-poet with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def to_item(self):
        return attr.asdict(self, recurse=False) 
Example #28
Source File: computation_utils.py    From federated with Apache License 2.0 5 votes vote down vote up
def update_state(state, **kwargs):
  """Returns a new `state` with new values for fields in `kwargs`.

  Args:
    state: the structure with named fields to update.
    **kwargs: the list of key-value pairs of fields to update in `state`.

  Raises:
    KeyError: if kwargs contains a field that is not in state.
    TypeError: if state is not a structure with named fields.
  """
  # TODO(b/129569441): Support AnonymousTuple as well.
  if not (py_typecheck.is_named_tuple(state) or py_typecheck.is_attrs(state) or
          isinstance(state, collections.Mapping)):
    raise TypeError('state must be a structure with named fields (e.g. '
                    'dict, attrs class, collections.namedtuple), '
                    'but found {}'.format(type(state)))
  if py_typecheck.is_named_tuple(state):
    d = state._asdict()
  elif py_typecheck.is_attrs(state):
    d = attr.asdict(state, dict_factory=collections.OrderedDict)
  else:
    for key in kwargs:
      if key not in state:
        raise KeyError(
            'state does not contain a field named "{!s}"'.format(key))
    d = state
  d.update(kwargs)
  if isinstance(state, collections.Mapping):
    return d
  return type(state)(**d) 
Example #29
Source File: chute.py    From Paradrop with Apache License 2.0 5 votes vote down vote up
def create_specification(self):
        """
        Create a new chute specification from the existing chute.

        This is a completely clean copy of all information necessary to rebuild
        the Chute object. It should contain only primitive types, which can
        easily be serialized as JSON or YAML.
        """
        def no_privates(a, _):
            return not a.name.startswith('_')

        return attr.asdict(self, filter=no_privates) 
Example #30
Source File: ui_settings.py    From aiohttp-swagger3 with Apache License 2.0 5 votes vote down vote up
def to_settings(self) -> Dict:
        return attr.asdict(
            self, filter=attr.filters.exclude(attr.fields(_UiSettings).path)
        )