Skip to content

Commit

Permalink
add unwrap methods to collection types + Null
Browse files Browse the repository at this point in the history
  • Loading branch information
syntapy committed Apr 19, 2022
1 parent e57b1df commit 52db08d
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 1 deletion.
22 changes: 22 additions & 0 deletions tomlkit/container.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,25 @@ def __init__(self, parsed: bool = False) -> None:
def body(self) -> List[Tuple[Optional[Key], Item]]:
return self._body

def unwrap(self, recursive: bool = True) -> str:
unwrapped = {}
for k, v in self._body:
if k is None:
continue

k = k.key
v = v.value

if isinstance(v, Container):
v = v.unwrap(recursive=recursive)

if k in unwrapped:
merge_dicts(unwrapped[k], v)
else:
unwrapped[k] = v.unwrap(recursive=recursive)

return unwrapped

@property
def value(self) -> Dict[Any, Any]:
d = {}
Expand Down Expand Up @@ -796,6 +815,9 @@ def __init__(self, container: Container, indices: Tuple[int]) -> None:
if k is not None:
dict.__setitem__(self, k.key, v)

def unwrap(self, recursive: bool = True) -> str:
return self._internal_container.unwrap(recursive=recursive)

@property
def value(self):
return self._internal_container.value
Expand Down
30 changes: 29 additions & 1 deletion tomlkit/items.py
Original file line number Diff line number Diff line change
Expand Up @@ -1078,6 +1078,15 @@ def __init__(self, value: list, trivia: Trivia, multiline: bool = False) -> None
self._multiline = multiline
self._reindex()

def unwrap(self, recursive: bool = True) -> str:
unwrapped = []
for v in self:
if recursive:
unwrapped.append(v.unwrap(recursive=recursive))
else:
unwrapped.append(v)
return unwrapped

@property
def discriminant(self) -> int:
return 8
Expand Down Expand Up @@ -1323,7 +1332,14 @@ def __init__(self, value: "container.Container", trivia: Trivia):
dict.__setitem__(self, k.key, v)

def unwrap(self, recursive: bool = True):
pass
unwrapped = {}
for k in self:
if recursive:
unwrapped[k] = self[k].unwrap(recursive=recursive)
else:
unwrapped[k] = self[k]

return unwrapped

@property
def value(self) -> "container.Container":
Expand Down Expand Up @@ -1708,6 +1724,15 @@ def __init__(
for table in body:
self.append(table)

def unwrap(self, recursive: bool = True) -> str:
unwrapped = []
for t in self._body:
if recursive:
unwrapped.append(t.unwrap(recursive=recursive))
else:
unwrapped.append(t)
return unwrapped

@property
def body(self) -> List[Table]:
return self._body
Expand Down Expand Up @@ -1799,6 +1824,9 @@ class Null(Item):
def __init__(self) -> None:
pass

def unwrap(self, recursive: bool = True) -> str:
return None

@property
def discriminant(self) -> int:
return -1
Expand Down

0 comments on commit 52db08d

Please sign in to comment.