Skip to content

Commit

Permalink
Update the type annotations to python 3.7+ style
Browse files Browse the repository at this point in the history
Signed-off-by: Frost Ming <me@frostming.com>
  • Loading branch information
frostming committed Apr 27, 2023
1 parent c7889d7 commit b727fe7
Show file tree
Hide file tree
Showing 8 changed files with 164 additions and 201 deletions.
6 changes: 3 additions & 3 deletions tomlkit/_compat.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
from __future__ import annotations

import contextlib
import sys

from typing import Any
from typing import List
from typing import Optional


PY38 = sys.version_info >= (3, 8)


def decode(string: Any, encodings: Optional[List[str]] = None):
def decode(string: Any, encodings: list[str] | None = None):
if not isinstance(string, bytes):
return string

Expand Down
5 changes: 3 additions & 2 deletions tomlkit/_utils.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from __future__ import annotations

import re

from collections.abc import Mapping
Expand All @@ -7,7 +9,6 @@
from datetime import timedelta
from datetime import timezone
from typing import Collection
from typing import Union

from tomlkit._compat import decode

Expand Down Expand Up @@ -41,7 +42,7 @@
_utc = timezone(timedelta(), "UTC")


def parse_rfc3339(string: str) -> Union[datetime, date, time]:
def parse_rfc3339(string: str) -> datetime | date | time:
m = RFC_3339_DATETIME.match(string)
if m:
year = int(m.group(1))
Expand Down
21 changes: 10 additions & 11 deletions tomlkit/api.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
from __future__ import annotations

import datetime as _datetime

from collections.abc import Mapping
from typing import IO
from typing import Iterable
from typing import Optional
from typing import Tuple
from typing import Union

from tomlkit._utils import parse_rfc3339
from tomlkit.container import Container
Expand Down Expand Up @@ -34,7 +33,7 @@
from tomlkit.toml_document import TOMLDocument


def loads(string: Union[str, bytes]) -> TOMLDocument:
def loads(string: str | bytes) -> TOMLDocument:
"""
Parses a string into a TOMLDocument.
Expand All @@ -59,7 +58,7 @@ def dumps(data: Mapping, sort_keys: bool = False) -> str:
raise TypeError(msg) from ex


def load(fp: Union[IO[str], IO[bytes]]) -> TOMLDocument:
def load(fp: IO[str] | IO[bytes]) -> TOMLDocument:
"""
Load toml document from a file-like object.
"""
Expand All @@ -76,7 +75,7 @@ def dump(data: Mapping, fp: IO[str], *, sort_keys: bool = False) -> None:
fp.write(dumps(data, sort_keys=sort_keys))


def parse(string: Union[str, bytes]) -> TOMLDocument:
def parse(string: str | bytes) -> TOMLDocument:
"""
Parses a string or bytes into a TOMLDocument.
"""
Expand All @@ -91,12 +90,12 @@ def document() -> TOMLDocument:


# Items
def integer(raw: Union[str, int]) -> Integer:
def integer(raw: str | int) -> Integer:
"""Create an integer item from a number or string."""
return item(int(raw))


def float_(raw: Union[str, float]) -> Float:
def float_(raw: str | float) -> Float:
"""Create an float item from a number or string."""
return item(float(raw))

Expand Down Expand Up @@ -175,7 +174,7 @@ def array(raw: str = None) -> Array:
return value(raw)


def table(is_super_table: Optional[bool] = None) -> Table:
def table(is_super_table: bool | None = None) -> Table:
"""Create an empty table.
:param is_super_table: if true, the table is a super table
Expand Down Expand Up @@ -224,7 +223,7 @@ def aot() -> AoT:
return AoT([])


def key(k: Union[str, Iterable[str]]) -> Key:
def key(k: str | Iterable[str]) -> Key:
"""Create a key from a string. When a list of string is given,
it will create a dotted key.
Expand Down Expand Up @@ -261,7 +260,7 @@ def value(raw: str) -> _Item:
return v


def key_value(src: str) -> Tuple[Key, _Item]:
def key_value(src: str) -> tuple[Key, _Item]:
"""Parse a key-value pair from a string.
:Example:
Expand Down
77 changes: 33 additions & 44 deletions tomlkit/container.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,9 @@
from __future__ import annotations

import copy

from typing import Any
from typing import Dict
from typing import Iterator
from typing import List
from typing import Optional
from typing import Tuple
from typing import Union

from tomlkit._compat import decode
from tomlkit._utils import merge_dicts
Expand Down Expand Up @@ -37,16 +34,16 @@ class Container(_CustomDict):
"""

def __init__(self, parsed: bool = False) -> None:
self._map: Dict[SingleKey, Union[int, Tuple[int, ...]]] = {}
self._body: List[Tuple[Optional[Key], Item]] = []
self._map: dict[SingleKey, int | tuple[int, ...]] = {}
self._body: list[tuple[Key | None, Item]] = []
self._parsed = parsed
self._table_keys = []

@property
def body(self) -> List[Tuple[Optional[Key], Item]]:
def body(self) -> list[tuple[Key | None, Item]]:
return self._body

def unwrap(self) -> Dict[str, Any]:
def unwrap(self) -> dict[str, Any]:
unwrapped = {}
for k, v in self.items():
if k is None:
Expand All @@ -66,7 +63,7 @@ def unwrap(self) -> Dict[str, Any]:
return unwrapped

@property
def value(self) -> Dict[str, Any]:
def value(self) -> dict[str, Any]:
d = {}
for k, v in self._body:
if k is None:
Expand Down Expand Up @@ -95,9 +92,7 @@ def parsing(self, parsing: bool) -> None:
for t in v.body:
t.value.parsing(parsing)

def add(
self, key: Union[Key, Item, str], item: Optional[Item] = None
) -> "Container":
def add(self, key: Key | Item | str, item: Item | None = None) -> Container:
"""
Adds an item to the current Container.
Expand Down Expand Up @@ -150,7 +145,7 @@ def _get_last_index_before_table(self) -> int:
last_index = i
return last_index + 1

def append(self, key: Union[Key, str, None], item: Item) -> "Container":
def append(self, key: Key | str | None, item: Item) -> Container:
"""Similar to :meth:`add` but both key and value must be given."""
if not isinstance(key, Key) and key is not None:
key = SingleKey(key)
Expand Down Expand Up @@ -333,7 +328,7 @@ def _remove_at(self, idx: int) -> None:
dict.__delitem__(self, key.key)
self._map.pop(key)

def remove(self, key: Union[Key, str]) -> "Container":
def remove(self, key: Key | str) -> Container:
"""Remove a key from the container."""
if not isinstance(key, Key):
key = SingleKey(key)
Expand All @@ -353,8 +348,8 @@ def remove(self, key: Union[Key, str]) -> "Container":
return self

def _insert_after(
self, key: Union[Key, str], other_key: Union[Key, str], item: Any
) -> "Container":
self, key: Key | str, other_key: Key | str, item: Any
) -> Container:
if key is None:
raise ValueError("Key cannot be null in insert_after()")

Expand Down Expand Up @@ -399,7 +394,7 @@ def _insert_after(

return self

def _insert_at(self, idx: int, key: Union[Key, str], item: Any) -> "Container":
def _insert_at(self, idx: int, key: Key | str, item: Any) -> Container:
if idx > len(self._body) - 1:
raise ValueError(f"Unable to insert at position {idx}")

Expand Down Expand Up @@ -445,7 +440,7 @@ def _insert_at(self, idx: int, key: Union[Key, str], item: Any) -> "Container":

return self

def item(self, key: Union[Key, str]) -> Item:
def item(self, key: Key | str) -> Item:
"""Get an item for the given key."""
if not isinstance(key, Key):
key = SingleKey(key)
Expand All @@ -462,7 +457,7 @@ def item(self, key: Union[Key, str]) -> Item:

return self._body[idx][1]

def last_item(self) -> Optional[Item]:
def last_item(self) -> Item | None:
"""Get the last item."""
if self._body:
return self._body[-1][1]
Expand All @@ -483,9 +478,7 @@ def as_string(self) -> str:

return s

def _render_table(
self, key: Key, table: Table, prefix: Optional[str] = None
) -> str:
def _render_table(self, key: Key, table: Table, prefix: str | None = None) -> str:
cur = ""

if table.display_name is not None:
Expand Down Expand Up @@ -554,7 +547,7 @@ def _render_aot(self, key, aot, prefix=None):

return cur

def _render_aot_table(self, table: Table, prefix: Optional[str] = None) -> str:
def _render_aot_table(self, table: Table, prefix: str | None = None) -> str:
cur = ""

_key = prefix or ""
Expand Down Expand Up @@ -614,7 +607,7 @@ def __iter__(self) -> Iterator[str]:
return iter(dict.keys(self))

# Dictionary methods
def __getitem__(self, key: Union[Key, str]) -> Union[Item, "Container"]:
def __getitem__(self, key: Key | str) -> Item | Container:
if not isinstance(key, Key):
key = SingleKey(key)

Expand All @@ -634,23 +627,21 @@ def __getitem__(self, key: Union[Key, str]) -> Union[Item, "Container"]:

return item

def __setitem__(self, key: Union[Key, str], value: Any) -> None:
def __setitem__(self, key: Key | str, value: Any) -> None:
if key is not None and key in self:
old_key = next(filter(lambda k: k == key, self._map))
self._replace(old_key, key, value)
else:
self.append(key, value)

def __delitem__(self, key: Union[Key, str]) -> None:
def __delitem__(self, key: Key | str) -> None:
self.remove(key)

def setdefault(self, key: Union[Key, str], default: Any) -> Any:
def setdefault(self, key: Key | str, default: Any) -> Any:
super().setdefault(key, default=default)
return self[key]

def _replace(
self, key: Union[Key, str], new_key: Union[Key, str], value: Item
) -> None:
def _replace(self, key: Key | str, new_key: Key | str, value: Item) -> None:
if not isinstance(key, Key):
key = SingleKey(key)

Expand All @@ -661,7 +652,7 @@ def _replace(
self._replace_at(idx, new_key, value)

def _replace_at(
self, idx: Union[int, Tuple[int]], new_key: Union[Key, str], value: Item
self, idx: int | tuple[int], new_key: Key | str, value: Item
) -> None:
value = _item(value)

Expand Down Expand Up @@ -757,10 +748,10 @@ def __setstate__(self, state):
if key is not None:
dict.__setitem__(self, key.key, item.value)

def copy(self) -> "Container":
def copy(self) -> Container:
return copy.copy(self)

def __copy__(self) -> "Container":
def __copy__(self) -> Container:
c = self.__class__(self._parsed)
for k, v in dict.items(self):
dict.__setitem__(c, k, v)
Expand All @@ -771,8 +762,8 @@ def __copy__(self) -> "Container":
return c

def _previous_item_with_index(
self, idx: Optional[int] = None, ignore=(Null,)
) -> Optional[Tuple[int, Item]]:
self, idx: int | None = None, ignore=(Null,)
) -> tuple[int, Item] | None:
"""Find the immediate previous item before index ``idx``"""
if idx is None or idx > len(self._body):
idx = len(self._body)
Expand All @@ -782,9 +773,7 @@ def _previous_item_with_index(
return i, v
return None

def _previous_item(
self, idx: Optional[int] = None, ignore=(Null,)
) -> Optional[Item]:
def _previous_item(self, idx: int | None = None, ignore=(Null,)) -> Item | None:
"""Find the immediate previous item before index ``idx``.
If ``idx`` is not given, the last item is returned.
"""
Expand All @@ -793,7 +782,7 @@ def _previous_item(


class OutOfOrderTableProxy(_CustomDict):
def __init__(self, container: Container, indices: Tuple[int]) -> None:
def __init__(self, container: Container, indices: tuple[int]) -> None:
self._container = container
self._internal_container = Container(True)
self._tables = []
Expand All @@ -818,13 +807,13 @@ def unwrap(self) -> str:
def value(self):
return self._internal_container.value

def __getitem__(self, key: Union[Key, str]) -> Any:
def __getitem__(self, key: Key | str) -> Any:
if key not in self._internal_container:
raise NonExistentKey(key)

return self._internal_container[key]

def __setitem__(self, key: Union[Key, str], item: Any) -> None:
def __setitem__(self, key: Key | str, item: Any) -> None:
if key in self._tables_map:
table = self._tables[self._tables_map[key]]
table[key] = item
Expand All @@ -846,7 +835,7 @@ def _remove_table(self, table: Table) -> None:
self._container._remove_at(idx)
break

def __delitem__(self, key: Union[Key, str]) -> None:
def __delitem__(self, key: Key | str) -> None:
if key in self._tables_map:
table = self._tables[self._tables_map[key]]
del table[key]
Expand All @@ -866,7 +855,7 @@ def __iter__(self) -> Iterator[str]:
def __len__(self) -> int:
return dict.__len__(self)

def setdefault(self, key: Union[Key, str], default: Any) -> Any:
def setdefault(self, key: Key | str, default: Any) -> Any:
super().setdefault(key, default=default)
return self[key]

Expand Down
Loading

0 comments on commit b727fe7

Please sign in to comment.