How to use the tomlkit.container.Container function in tomlkit

To help you get started, we’ve selected a few tomlkit examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github sdispater / tomlkit / tomlkit / items.py View on Github external
return Float(value, Trivia(), str(value))
    elif isinstance(value, dict):
        val = Table(Container(), Trivia(), False)
        for k, v in sorted(value.items(), key=lambda i: (isinstance(i[1], dict), i[0])):
            val[k] = item(v, _parent=val)

        return val
    elif isinstance(value, list):
        if value and isinstance(value[0], dict):
            a = AoT([])
        else:
            a = Array([], Trivia())

        for v in value:
            if isinstance(v, dict):
                table = Table(Container(), Trivia(), True)

                for k, _v in sorted(
                    v.items(), key=lambda i: (isinstance(i[1], dict), i[0])
                ):
                    i = item(_v)
                    if isinstance(table, InlineTable):
                        i.trivia.trail = ""

                    table[k] = item(i)

                v = table

            a.append(v)

        return a
    elif isinstance(value, (str, unicode)):
github pypa / pipenv / pipenv / vendor / requirementslib / models / utils.py View on Github external
Variable as PkgResourcesVariable,
        Value as PkgResourcesValue,
        Marker as PkgResourcesMarker,
    )
    from pip_shims.shims import Link
    from vistir.compat import Path

    _T = TypeVar("_T")
    TMarker = Union[Marker, PkgResourcesMarker]
    TVariable = TypeVar("TVariable", PkgResourcesVariable, Variable)
    TValue = TypeVar("TValue", PkgResourcesValue, Value)
    TOp = TypeVar("TOp", PkgResourcesOp, Op)
    MarkerTuple = Tuple[TVariable, TOp, TValue]
    TRequirement = Union[PackagingRequirement, PkgResourcesRequirement]
    STRING_TYPE = Union[bytes, str, Text]
    TOML_DICT_TYPES = Union[Container, Package, PackageCollection, Table, InlineTable]
    S = TypeVar("S", bytes, str, Text)


TOML_DICT_OBJECTS = (Container, Package, Table, InlineTable, PackageCollection)
TOML_DICT_NAMES = [o.__class__.__name__ for o in TOML_DICT_OBJECTS]

HASH_STRING = " --hash={0}"

ALPHA_NUMERIC = r"[{0}{1}]".format(string.ascii_letters, string.digits)
PUNCTUATION = r"[\-_\.]"
ALPHANUM_PUNCTUATION = r"[{0}{1}\-_\.]".format(string.ascii_letters, string.digits)
NAME = r"{0}+{1}*{2}".format(ALPHANUM_PUNCTUATION, PUNCTUATION, ALPHA_NUMERIC)
REF = r"[{0}{1}\-\_\./]".format(string.ascii_letters, string.digits)
EXTRAS = r"(?P\[{0}(?:,{0})*\])".format(NAME)
NAME_WITH_EXTRAS = r"(?P{0}){1}?".format(NAME, EXTRAS)
NAME_RE = re.compile(NAME_WITH_EXTRAS)
github sdispater / tomlkit / tomlkit / container.py View on Github external
if key is not None and not isinstance(current, Table):
                raise KeyAlreadyPresent(key)

            # Adding sub tables to a currently existing table
            idx = self._map[key]
            if not isinstance(idx, tuple):
                idx = (idx,)

            self._map[key] = idx + (len(self._body),)
        else:
            self._map[key] = len(self._body)

        self._body.append((key, item))

        if key is not None:
            super(Container, self).__setitem__(key.key, item.value)

        return self
github sdispater / tomlkit / tomlkit / parser.py View on Github external
raise self.parse_error(EmptyTableNameError)

        key = Key(name, sep="")
        name_parts = tuple(self._split_table_name(name))
        missing_table = False
        if parent_name:
            parent_name_parts = tuple(self._split_table_name(parent_name))
        else:
            parent_name_parts = tuple()

        if len(name_parts) > len(parent_name_parts) + 1:
            missing_table = True

        name_parts = name_parts[len(parent_name_parts) :]

        values = Container(True)

        self.inc()  # Skip closing bracket
        if is_aot:
            # TODO: Verify close bracket
            self.inc()

        cws, comment, trail = self._parse_comment_trail()

        result = Null()
        table = Table(
            values,
            Trivia(indent, cws, comment, trail),
            is_aot,
            name=name,
            display_name=name,
        )
github sdispater / tomlkit / tomlkit / container.py View on Github external
def __getitem__(self, key):  # type: (Union[Key, str]) -> Union[Item, Container]
        if not isinstance(key, Key):
            key = Key(key)

        idx = self._map.get(key, None)
        if idx is None:
            raise NonExistentKey(key)

        if isinstance(idx, tuple):
            container = Container(True)

            for i in idx:
                item = self._body[i][1]

                if isinstance(item, Table):
                    for k, v in item.value.body:
                        container.append(k, v)
                else:
                    container.append(key, item)

            return container

        item = self._body[idx][1]

        if item.is_boolean():
            return item.value
github sdispater / tomlkit / tomlkit / container.py View on Github external
def value(self):  # type: () -> Dict[Any, Any]
        d = {}
        for k, v in self._body:
            if k is None:
                continue

            k = k.key
            v = v.value

            if isinstance(v, Container):
                v = v.value

            if k in d:
                d[k].update(v)
            else:
                d[k] = v

        return d
github sarugaku / requirementslib / src / requirementslib / models / utils.py View on Github external
value_type = type(toml_dict).__name__
    if toml_dict is None:
        raise TypeError("Invalid type NoneType when converting toml dict to python")
    converted = None  # type: Optional[Dict]
    if isinstance(toml_dict, (InlineTable, Table)) or value_type in (
        "InlineTable",
        "Table",
    ):
        converted = toml_dict.value
    elif isinstance(toml_dict, (Package, PackageCollection)) or value_type in (
        "Package, PackageCollection"
    ):
        converted = toml_dict._data
        if isinstance(converted, Container) or type(converted).__name__ == "Container":
            converted = converted.value
    elif isinstance(toml_dict, Container) or value_type == "Container":
        converted = toml_dict.value
    elif isinstance(toml_dict, dict):
        converted = toml_dict.copy()
    else:
        raise TypeError(
            "Invalid type for conversion: expected Container, Dict, or Table, "
            "got {0!r}".format(toml_dict)
        )
    if isinstance(converted, dict):
        return {k: tomlkit_value_to_python(v) for k, v in converted.items()}
    elif isinstance(converted, (TOML_DICT_OBJECTS)) or value_type in TOML_DICT_NAMES:
        return tomlkit_dict_to_python(converted)
    return converted
github sarugaku / requirementslib / src / requirementslib / models / utils.py View on Github external
def tomlkit_dict_to_python(toml_dict):
    # type: (TOML_DICT_TYPES) -> Dict
    value_type = type(toml_dict).__name__
    if toml_dict is None:
        raise TypeError("Invalid type NoneType when converting toml dict to python")
    converted = None  # type: Optional[Dict]
    if isinstance(toml_dict, (InlineTable, Table)) or value_type in (
        "InlineTable",
        "Table",
    ):
        converted = toml_dict.value
    elif isinstance(toml_dict, (Package, PackageCollection)) or value_type in (
        "Package, PackageCollection"
    ):
        converted = toml_dict._data
        if isinstance(converted, Container) or type(converted).__name__ == "Container":
            converted = converted.value
    elif isinstance(toml_dict, Container) or value_type == "Container":
        converted = toml_dict.value
    elif isinstance(toml_dict, dict):
        converted = toml_dict.copy()
    else:
        raise TypeError(
            "Invalid type for conversion: expected Container, Dict, or Table, "
            "got {0!r}".format(toml_dict)
        )
    if isinstance(converted, dict):
        return {k: tomlkit_value_to_python(v) for k, v in converted.items()}
    elif isinstance(converted, (TOML_DICT_OBJECTS)) or value_type in TOML_DICT_NAMES:
        return tomlkit_dict_to_python(converted)
    return converted
github sdispater / tomlkit / tomlkit / parser.py View on Github external
values,
            Trivia(indent, cws, comment, trail),
            is_aot,
            name=name,
            display_name=name,
        )

        if len(name_parts) > 1:
            if missing_table:
                # Missing super table
                # i.e. a table initialized like this: [foo.bar]
                # without initializing [foo]
                #
                # So we have to create the parent tables
                table = Table(
                    Container(True),
                    Trivia(indent, cws, comment, trail),
                    is_aot and name_parts[0].key in self._aot_stack,
                    is_super_table=True,
                    name=name_parts[0].key,
                )

                result = table
                key = name_parts[0]

                for i, _name in enumerate(name_parts[1:]):
                    if _name in table:
                        child = table[_name]
                    else:
                        child = Table(
                            Container(True),
                            Trivia(indent, cws, comment, trail),