Python types.MappingProxyType() Examples

The following are 30 code examples of types.MappingProxyType(). 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 types , or try the search function .
Example #1
Source File: data_formats.py    From pycoalaip with Apache License 2.0 7 votes vote down vote up
def _make_context_immutable(context):
    """Best effort attempt at turning a properly formatted context
    (either a string, dict, or array of strings and dicts) into an
    immutable data structure.

    If we get an array, make it immutable by creating a tuple; if we get
    a dict, copy it into a MappingProxyType. Otherwise, return as-is.
    """
    def make_immutable(val):
        if isinstance(val, Mapping):
            return MappingProxyType(val)
        else:
            return val

    if not isinstance(context, (str, Mapping)):
        try:
            return tuple([make_immutable(val) for val in context])
        except TypeError:
            pass
    return make_immutable(context) 
Example #2
Source File: h5ad.py    From anndata with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def write_sparse_as_dense(f, key, value, dataset_kwargs=MappingProxyType({})):
    real_key = None  # Flag for if temporary key was used
    if key in f:
        if (
            isinstance(value, (h5py.Group, h5py.Dataset, SparseDataset))
            and value.file.filename == f.filename
        ):  # Write to temporary key before overwriting
            real_key = key
            # Transform key to temporary, e.g. raw/X -> raw/_X, or X -> _X
            key = re.sub(r"(.*)(\w(?!.*/))", r"\1_\2", key.rstrip("/"))
        else:
            del f[key]  # Wipe before write
    dset = f.create_dataset(key, shape=value.shape, dtype=value.dtype, **dataset_kwargs)
    compressed_axis = int(isinstance(value, sparse.csc_matrix))
    for idx in idx_chunks_along_axis(value.shape, compressed_axis, 1000):
        dset[idx] = value[idx].toarray()
    if real_key is not None:
        del f[real_key]
        f[real_key] = f[key]
        del f[key] 
Example #3
Source File: format_checks.py    From godot-gdscript-toolkit with MIT License 6 votes vote down vote up
def lint(gdscript_code: str, config: MappingProxyType) -> List[Problem]:
    disable = config["disable"]
    checks_to_run_w_code = [
        (
            "max-line-length",
            partial(_max_line_length_check, config["max-line-length"]),
        ),
        ("max-file-lines", partial(_max_file_lines_check, config["max-file-lines"]),),
        ("trailing-whitespace", _trailing_ws_check,),
        ("mixed-tabs-and-spaces", _mixed_tabs_and_spaces_check,),
    ]  # type: List[Tuple[str, Callable]]
    problem_clusters = map(
        lambda x: x[1](gdscript_code) if x[0] not in disable else [],
        checks_to_run_w_code,
    )
    problems = [problem for cluster in problem_clusters for problem in cluster]
    return problems 
Example #4
Source File: utils.py    From aiohttp_admin with Apache License 2.0 6 votes vote down vote up
def validate_query(query, possible_columns):
    q = validate_query_structure(query)
    sort_field = q.get('_sortField')

    filters = q.get('_filters', [])
    columns = [field_name for field_name in filters]

    if sort_field is not None:
        columns.append(sort_field)

    not_valid = set(columns).difference(
        possible_columns + [MULTI_FIELD_TEXT_QUERY])
    if not_valid:
        column_list = ', '.join(not_valid)
        msg = 'Columns: {} do not present in resource'.format(column_list)
        raise JsonValidaitonError(msg)
    return MappingProxyType(q) 
Example #5
Source File: lexer.py    From edgedb with Apache License 2.0 6 votes vote down vote up
def __init_subclass__(cls):
        if not hasattr(cls, 'states'):
            return

        re_states = {}
        for state, rules in cls.states.items():
            res = []
            for rule in rules:
                if cls.asbytes:
                    res.append(b'(?P<%b>%b)' % (rule.id.encode(), rule.regexp))
                else:
                    res.append('(?P<{}>{})'.format(rule.id, rule.regexp))

            if cls.asbytes:
                res.append(b'(?P<err>.)')
            else:
                res.append('(?P<err>.)')

            if cls.asbytes:
                full_re = b' | '.join(res)
            else:
                full_re = ' | '.join(res)
            re_states[state] = re.compile(full_re, cls.RE_FLAGS)

        cls.re_states = types.MappingProxyType(re_states) 
Example #6
Source File: h5ad.py    From anndata with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def write_none(f, key, value, dataset_kwargs=MappingProxyType({})):
    pass 
Example #7
Source File: cloudpickle.py    From pywren-ibm-cloud with Apache License 2.0 5 votes vote down vote up
def save_mappingproxy(self, obj):
            self.save_reduce(types.MappingProxyType, (dict(obj),), obj=obj) 
Example #8
Source File: dataclasses.py    From pyquil with Apache License 2.0 5 votes vote down vote up
def __init__(self, default, default_factory, init, repr, hash, compare,
                 metadata):
        self.name = None
        self.type = None
        self.default = default
        self.default_factory = default_factory
        self.init = init
        self.repr = repr
        self.hash = hash
        self.compare = compare
        self.metadata = (_EMPTY_METADATA
                         if metadata is None or len(metadata) == 0 else
                         types.MappingProxyType(metadata))
        self._field_type = None 
Example #9
Source File: h5ad.py    From anndata with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def write_sparse_compressed(
    f, key, value, fmt: Literal["csr", "csc"], dataset_kwargs=MappingProxyType({})
):
    g = f.create_group(key)
    g.attrs["encoding-type"] = f"{fmt}_matrix"
    g.attrs["encoding-version"] = EncodingVersions[f"{fmt}_matrix"].value
    g.attrs["shape"] = value.shape

    # Allow resizing
    if "maxshape" not in dataset_kwargs:
        dataset_kwargs = dict(maxshape=(None,), **dataset_kwargs)

    g.create_dataset("data", data=value.data, **dataset_kwargs)
    g.create_dataset("indices", data=value.indices, **dataset_kwargs)
    g.create_dataset("indptr", data=value.indptr, **dataset_kwargs) 
Example #10
Source File: h5ad.py    From anndata with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def write_sparse_dataset(f, key, value, dataset_kwargs=MappingProxyType({})):
    write_sparse_compressed(
        f, key, value.to_backed(), fmt=value.format_str, dataset_kwargs=dataset_kwargs,
    ) 
Example #11
Source File: h5ad.py    From anndata with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def write_array(f, key, value, dataset_kwargs=MappingProxyType({})):
    # Convert unicode to fixed length strings
    if value.dtype.kind in {"U", "O"}:
        value = value.astype(h5py.special_dtype(vlen=str))
    elif value.dtype.names is not None:
        value = _to_hdf5_vlen_strings(value)
    f.create_dataset(key, data=value, **dataset_kwargs) 
Example #12
Source File: h5ad.py    From anndata with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def write_basic(f, key, value, dataset_kwargs=MappingProxyType({})):
    f.create_dataset(key, data=value, **dataset_kwargs) 
Example #13
Source File: h5ad.py    From anndata with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def write_not_implemented(f, key, value, dataset_kwargs=MappingProxyType({})):
    # If it’s not an array, try and make it an array. If that fails, pickle it.
    # Maybe rethink that, maybe this should just pickle,
    # and have explicit implementations for everything else
    raise NotImplementedError(
        f"Failed to write value for {key}, "
        f"since a writer for type {type(value)} has not been implemented yet."
    ) 
Example #14
Source File: h5ad.py    From anndata with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def write_raw(f, key, value, dataset_kwargs=MappingProxyType({})):
    group = f.create_group(key)
    group.attrs["encoding-type"] = "raw"
    group.attrs["encoding-version"] = EncodingVersions.raw.value
    group.attrs["shape"] = value.shape
    write_attribute(f, "raw/X", value.X, dataset_kwargs=dataset_kwargs)
    write_attribute(f, "raw/var", value.var, dataset_kwargs=dataset_kwargs)
    write_attribute(f, "raw/varm", value.varm, dataset_kwargs=dataset_kwargs) 
Example #15
Source File: __init__.py    From rules_pip with MIT License 5 votes vote down vote up
def parameters(self):
        try:
            return types.MappingProxyType(self._parameters)
        except AttributeError:
            return OrderedDict(self._parameters.items()) 
Example #16
Source File: h5ad.py    From anndata with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def write_list(f, key, value, dataset_kwargs=MappingProxyType({})):
    write_array(f, key, np.array(value), dataset_kwargs=dataset_kwargs) 
Example #17
Source File: data.py    From dffml with MIT License 5 votes vote down vote up
def export_dict(**kwargs):
    """
    Return the dict given as kwargs but first recurse into each element and call
    its export or _asdict function if it is not a serializable type.
    """
    for key, value in kwargs.items():
        export_value(kwargs, key, value)
        if isinstance(kwargs[key], (dict, types.MappingProxyType)):
            kwargs[key] = export_dict(**kwargs[key])
        elif isinstance(kwargs[key], list):
            kwargs[key] = export_list(kwargs[key])
    return kwargs 
Example #18
Source File: data.py    From dffml with MIT License 5 votes vote down vote up
def export_list(iterable):
    for i, value in enumerate(iterable):
        export_value(iterable, i, value)
        if isinstance(value, (dict, types.MappingProxyType)):
            iterable[i] = export_dict(**iterable[i])
        elif dataclasses.is_dataclass(value):
            iterable[i] = export_dict(**dataclasses.asdict(value))
        elif isinstance(value, list):
            iterable[i] = export_list(iterable[i])
    return iterable 
Example #19
Source File: enum.py    From Imogen with MIT License 5 votes vote down vote up
def __members__(cls):
        """Returns a mapping of member name->value.

        This mapping lists all enum members, including aliases. Note that this
        is a read-only view of the internal mapping.

        """
        return MappingProxyType(cls._member_map_) 
Example #20
Source File: dataclasses.py    From Imogen with MIT License 5 votes vote down vote up
def __init__(self, default, default_factory, init, repr, hash, compare,
                 metadata):
        self.name = None
        self.type = None
        self.default = default
        self.default_factory = default_factory
        self.init = init
        self.repr = repr
        self.hash = hash
        self.compare = compare
        self.metadata = (_EMPTY_METADATA
                         if metadata is None or len(metadata) == 0 else
                         types.MappingProxyType(metadata))
        self._field_type = None 
Example #21
Source File: headerregistry.py    From Imogen with MIT License 5 votes vote down vote up
def params(self):
        return MappingProxyType(self._params) 
Example #22
Source File: dataclasses.py    From graphene with MIT License 5 votes vote down vote up
def __init__(self, default, default_factory, init, repr, hash, compare, metadata):
        self.name = None
        self.type = None
        self.default = default
        self.default_factory = default_factory
        self.init = init
        self.repr = repr
        self.hash = hash
        self.compare = compare
        self.metadata = (
            _EMPTY_METADATA
            if metadata is None or len(metadata) == 0
            else types.MappingProxyType(metadata)
        )
        self._field_type = None 
Example #23
Source File: test_pprint.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def test_mapping_proxy(self):
        words = 'the quick brown fox jumped over a lazy dog'.split()
        d = dict(zip(words, itertools.count()))
        m = types.MappingProxyType(d)
        self.assertEqual(pprint.pformat(m), """\
mappingproxy({'a': 6,
              'brown': 2,
              'dog': 8,
              'fox': 3,
              'jumped': 4,
              'lazy': 7,
              'over': 5,
              'quick': 1,
              'the': 0})""")
        d = collections.OrderedDict(zip(words, itertools.count()))
        m = types.MappingProxyType(d)
        self.assertEqual(pprint.pformat(m), """\
mappingproxy(OrderedDict([('the', 0),
                          ('quick', 1),
                          ('brown', 2),
                          ('fox', 3),
                          ('jumped', 4),
                          ('over', 5),
                          ('a', 6),
                          ('lazy', 7),
                          ('dog', 8)]))""") 
Example #24
Source File: enum.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def __members__(cls):
        """Returns a mapping of member name->value.

        This mapping lists all enum members, including aliases. Note that this
        is a read-only view of the internal mapping.

        """
        return MappingProxyType(cls._member_map_) 
Example #25
Source File: utils.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def isNonPrimitiveInstance(x):
        return not isinstance(x,(float,int,type,tuple,list,dict,str,bytes,complex,bool,slice,_rl_NoneType,
            types.FunctionType,types.LambdaType,types.CodeType,
            types.MappingProxyType,types.SimpleNamespace,
            types.GeneratorType,types.MethodType,types.BuiltinFunctionType,
            types.BuiltinMethodType,types.ModuleType,types.TracebackType,
            types.FrameType,types.GetSetDescriptorType,types.MemberDescriptorType)) 
Example #26
Source File: headerregistry.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def params(self):
        return MappingProxyType(self._params) 
Example #27
Source File: enum.py    From GraphicDesignPatternByPython with MIT License 5 votes vote down vote up
def __members__(cls):
        """Returns a mapping of member name->value.

        This mapping lists all enum members, including aliases. Note that this
        is a read-only view of the internal mapping.

        """
        return MappingProxyType(cls._member_map_) 
Example #28
Source File: _compat.py    From pipenv with MIT License 5 votes vote down vote up
def metadata_proxy(d):
        return types.MappingProxyType(dict(d)) 
Example #29
Source File: __init__.py    From pipenv with MIT License 5 votes vote down vote up
def parameters(self):
        try:
            return types.MappingProxyType(self._parameters)
        except AttributeError:
            return OrderedDict(self._parameters.items()) 
Example #30
Source File: _queries.py    From scanpy with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _enrich_anndata(
    adata: AnnData,
    group: str,
    *,
    org: Optional[str] = "hsapiens",
    key: str = "rank_genes_groups",
    pval_cutoff: float = 0.05,
    log2fc_min: Optional[float] = None,
    log2fc_max: Optional[float] = None,
    gene_symbols: Optional[str] = None,
    gprofiler_kwargs: Mapping[str, Any] = MappingProxyType({}),
) -> pd.DataFrame:
    de = rank_genes_groups_df(
        adata,
        group=group,
        key=key,
        pval_cutoff=pval_cutoff,
        log2fc_min=log2fc_min,
        log2fc_max=log2fc_max,
        gene_symbols=gene_symbols,
    )
    if gene_symbols is not None:
        gene_list = list(de[gene_symbols].dropna())
    else:
        gene_list = list(de["names"].dropna())
    return enrich(gene_list, org=org, gprofiler_kwargs=gprofiler_kwargs)