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: 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 #3
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 #4
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 #5
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 #6
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 #7
Source File: inspect.py    From jawfish with MIT License 5 votes vote down vote up
def __init__(self, parameters=None, *, return_annotation=_empty,
                 __validate_parameters__=True):
        '''Constructs Signature from the given list of Parameter
        objects and 'return_annotation'.  All arguments are optional.
        '''

        if parameters is None:
            params = OrderedDict()
        else:
            if __validate_parameters__:
                params = OrderedDict()
                top_kind = _POSITIONAL_ONLY

                for idx, param in enumerate(parameters):
                    kind = param.kind
                    if kind < top_kind:
                        msg = 'wrong parameter order: {} before {}'
                        msg = msg.format(top_kind, param.kind)
                        raise ValueError(msg)
                    else:
                        top_kind = kind

                    name = param.name
                    if name is None:
                        name = str(idx)
                        param = param.replace(name=name)

                    if name in params:
                        msg = 'duplicate parameter name: {!r}'.format(name)
                        raise ValueError(msg)
                    params[name] = param
            else:
                params = OrderedDict(((param.name, param)
                                                for param in parameters))

        self._parameters = types.MappingProxyType(params)
        self._return_annotation = return_annotation 
Example #8
Source File: funcsigs.py    From tangent with Apache License 2.0 5 votes vote down vote up
def parameters(self):
    try:
      return types.MappingProxyType(self._parameters)
    except AttributeError:
      return OrderedDict(self._parameters.items()) 
Example #9
Source File: basekeyparser.py    From qutebrowser with GNU General Public License v3.0 5 votes vote down vote up
def _match_key_mapping(
            self, sequence: keyutils.KeySequence) -> MatchResult:
        """Try to match a key in bindings.key_mappings."""
        self._debug_log("Trying match with key_mappings")
        mapped = sequence.with_mappings(
            types.MappingProxyType(config.cache['bindings.key_mappings']))
        if sequence != mapped:
            self._debug_log("Mapped {} -> {}".format(
                sequence, mapped))
            return self._match_key(mapped)
        return MatchResult(match_type=QKeySequence.NoMatch,
                           command=None,
                           sequence=sequence) 
Example #10
Source File: connection.py    From aioredis with MIT License 5 votes vote down vote up
def pubsub_channels(self):
        """Returns read-only channels dict."""
        return types.MappingProxyType(self._pubsub_channels) 
Example #11
Source File: connection.py    From aioredis with MIT License 5 votes vote down vote up
def pubsub_patterns(self):
        """Returns read-only patterns dict."""
        return types.MappingProxyType(self._pubsub_patterns) 
Example #12
Source File: pubsub.py    From aioredis with MIT License 5 votes vote down vote up
def channels(self):
        """Read-only channels dict."""
        return types.MappingProxyType({
            ch.name: ch for ch in self._refs.values()
            if not ch.is_pattern}) 
Example #13
Source File: pubsub.py    From aioredis with MIT License 5 votes vote down vote up
def patterns(self):
        """Read-only patterns dict."""
        return types.MappingProxyType({
            ch.name: ch for ch in self._refs.values()
            if ch.is_pattern}) 
Example #14
Source File: pool.py    From aioredis with MIT License 5 votes vote down vote up
def pubsub_channels(self):
        if self._pubsub_conn and not self._pubsub_conn.closed:
            return self._pubsub_conn.pubsub_channels
        return types.MappingProxyType({}) 
Example #15
Source File: entity.py    From calm-dsl with Apache License 2.0 5 votes vote down vote up
def __init_subclass__(cls, **kwargs):
        super().__init_subclass__(**kwargs)

        if not hasattr(cls, "__schema_name__"):
            raise TypeError("Entity type does not have a schema name")

        schema_name = getattr(cls, "__schema_name__")
        cls.subclasses[schema_name] = cls

        # Handle base case (Entity)
        if not schema_name:
            return

        # Set properties on metaclass by fetching from schema
        (schema_props, validators, defaults, display_map) = get_schema_details(
            schema_name
        )

        # Set validator dict on metaclass for each prop.
        # To be used during __setattr__() to validate props.
        # Look at validate() for details.
        setattr(cls, "__validator_dict__", MappingProxyType(validators))

        # Set defaults which will be used during serialization.
        # Look at json_dumps() for details
        setattr(cls, "__default_attrs__", MappingProxyType(defaults))

        # Attach schema properties to metaclass
        setattr(cls, "__schema_props__", MappingProxyType(schema_props))

        # Attach display map for compile/decompile
        setattr(cls, "__display_map__", MappingProxyType(display_map)) 
Example #16
Source File: dataclasses.py    From dataclasses 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 #17
Source File: enums.py    From discord.py with MIT License 5 votes vote down vote up
def __members__(cls):
        return types.MappingProxyType(cls._enum_member_map_) 
Example #18
Source File: bot.py    From discord.py with MIT License 5 votes vote down vote up
def cogs(self):
        """Mapping[:class:`str`, :class:`Cog`]: A read-only mapping of cog name to cog."""
        return types.MappingProxyType(self.__cogs)

    # extensions 
Example #19
Source File: bot.py    From discord.py with MIT License 5 votes vote down vote up
def extensions(self):
        """Mapping[:class:`str`, :class:`py:types.ModuleType`]: A read-only mapping of extension name to extension."""
        return types.MappingProxyType(self.__extensions)

    # help command stuff 
Example #20
Source File: _compat.py    From python-netsurv with MIT License 5 votes vote down vote up
def metadata_proxy(d):
        return types.MappingProxyType(dict(d)) 
Example #21
Source File: _compat.py    From python-netsurv with MIT License 5 votes vote down vote up
def metadata_proxy(d):
        return types.MappingProxyType(dict(d)) 
Example #22
Source File: stringparser.py    From bob with GNU General Public License v3.0 5 votes vote down vote up
def inspect(self):
        return MappingProxyType(self.data) 
Example #23
Source File: __init__.py    From auto-alt-text-lambda-api 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 #24
Source File: functions.py    From edgedb with Apache License 2.0 5 votes vote down vote up
def find_named_only(
        self,
        schema: s_schema.Schema,
    ) -> Mapping[str, Parameter]:
        named = {}
        for param in self.objects(schema):
            if param.get_kind(schema) is ft.ParameterKind.NAMED_ONLY:
                named[param.get_parameter_name(schema)] = param

        return types.MappingProxyType(named) 
Example #25
Source File: types.py    From edgedb with Apache License 2.0 5 votes vote down vote up
def create(
        cls: typing.Type[Tuple_T],
        schema: s_schema.Schema,
        *,
        name: Optional[str] = None,
        id: Union[uuid.UUID, so.NoDefaultT] = so.NoDefault,
        element_types: Mapping[str, Type],
        named: bool = False,
        **kwargs: Any,
    ) -> typing.Tuple[s_schema.Schema, Tuple_T]:
        element_types = types.MappingProxyType(element_types)
        if id is so.NoDefault:
            quals = []
            if name is not None:
                quals.append(name)
            id = generate_tuple_type_id(schema, element_types, named, *quals)

        if name is None:
            st_names = ', '.join(
                st.get_displayname(schema) for st in element_types.values()
            )
            name = type_name_from_id_and_displayname(id, f'tuple<{st_names}>')

        result = typing.cast(Tuple_T, schema.get_by_id(id, default=None))
        if result is None:
            schema, result = super().create_in_schema(
                schema,
                id=id,
                name=name,
                named=named,
                element_types=element_types,
                **kwargs,
            )

        return schema, result 
Example #26
Source File: funcsigs.py    From mlens 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 #27
Source File: block.py    From godot-gdscript-toolkit with MIT License 5 votes vote down vote up
def format_block(
    statements: List[Node],
    statement_formatter: Callable,
    context: Context,
    surrounding_empty_lines_table: MappingProxyType = DEFAULT_SURROUNDINGS_TABLE,
) -> Outcome:
    previous_statement_name = None
    formatted_lines = []  # type: FormattedLines
    previously_processed_line_number = context.previously_processed_line_number
    for statement in statements:
        blank_lines = reconstruct_blank_lines_in_range(
            previously_processed_line_number, statement.line, context,
        )
        if previous_statement_name is None:
            blank_lines = _remove_empty_strings_from_begin(blank_lines)
        else:
            blank_lines = _add_extra_blanks_due_to_previous_statement(
                blank_lines,
                previous_statement_name,  # type: ignore
                surrounding_empty_lines_table,
            )
            blank_lines = _add_extra_blanks_due_to_next_statement(
                blank_lines, statement.data, surrounding_empty_lines_table
            )
        formatted_lines += blank_lines
        lines, previously_processed_line_number = statement_formatter(
            statement, context
        )
        formatted_lines += lines
        previous_statement_name = statement.data
    dedent_line_number = _find_dedent_line_number(
        previously_processed_line_number, context
    )
    lines_at_the_end = reconstruct_blank_lines_in_range(
        previously_processed_line_number, dedent_line_number, context,
    )
    lines_at_the_end = _remove_empty_strings_from_end(lines_at_the_end)
    formatted_lines += lines_at_the_end
    previously_processed_line_number = dedent_line_number - 1
    return (formatted_lines, previously_processed_line_number) 
Example #28
Source File: block.py    From godot-gdscript-toolkit with MIT License 5 votes vote down vote up
def _add_extra_blanks_due_to_previous_statement(
    blank_lines: FormattedLines,
    previous_statement_name: str,
    surrounding_empty_lines_table: MappingProxyType,
) -> FormattedLines:
    # assumption: there is no sequence of empty lines longer than 1 (in blank lines)
    forced_blanks_num = surrounding_empty_lines_table.get(previous_statement_name)
    if forced_blanks_num is None:
        return blank_lines
    lines_to_prepend = forced_blanks_num
    lines_to_prepend -= 1 if len(blank_lines) > 0 and blank_lines[0][1] == "" else 0
    empty_line = [(None, "")]  # type: FormattedLines
    return lines_to_prepend * empty_line + blank_lines 
Example #29
Source File: block.py    From godot-gdscript-toolkit with MIT License 5 votes vote down vote up
def _add_extra_blanks_due_to_next_statement(
    blank_lines: FormattedLines,
    next_statement_name: str,
    surrounding_empty_lines_table: MappingProxyType,
) -> FormattedLines:
    # assumption: there is no sequence of empty lines longer than 2 (in blank lines)
    forced_blanks_num = surrounding_empty_lines_table.get(next_statement_name)
    if forced_blanks_num is None:
        return blank_lines
    first_empty_line_ix_from_end = _find_first_empty_line_ix_from_end(blank_lines)
    empty_lines_already_in_place = 1 if first_empty_line_ix_from_end > -1 else 0
    empty_lines_already_in_place += (
        1
        if first_empty_line_ix_from_end > 0
        and blank_lines[first_empty_line_ix_from_end - 1][1] == ""
        else 0
    )
    lines_to_inject = forced_blanks_num
    lines_to_inject -= empty_lines_already_in_place
    empty_line = [(None, "")]  # type: FormattedLines
    if first_empty_line_ix_from_end == -1:
        return lines_to_inject * empty_line + blank_lines
    return (
        blank_lines[:first_empty_line_ix_from_end]
        + lines_to_inject * empty_line
        + blank_lines[first_empty_line_ix_from_end:]
    ) 
Example #30
Source File: __init__.py    From godot-gdscript-toolkit with MIT License 5 votes vote down vote up
def lint_code(
    gdscript_code: str, config: MappingProxyType = DEFAULT_CONFIG
) -> List[Problem]:
    parse_tree = parser.parse(gdscript_code, gather_metadata=True)
    problems = design_checks.lint(parse_tree, config)
    problems += format_checks.lint(gdscript_code, config)
    problems += name_checks.lint(parse_tree, config)
    problems += class_checks.lint(parse_tree, config)
    problems += basic_checks.lint(parse_tree, config)
    return problems