Skip to content

Commit

Permalink
chore: use from __future__ import annotations
Browse files Browse the repository at this point in the history
  • Loading branch information
5j9 committed Oct 17, 2024
1 parent 5011c91 commit 78c96fb
Show file tree
Hide file tree
Showing 16 changed files with 165 additions and 156 deletions.
1 change: 1 addition & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ line-length = 79
format.quote-style = 'single'
lint.isort.combine-as-imports = true
lint.extend-select = [
'FA', # flake8-future-annotations
'I', # isort
'UP', # pyupgrade
]
Expand Down
4 changes: 2 additions & 2 deletions tests/test_spans.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from typing import Dict, List
from __future__ import annotations

from pytest import mark

Expand All @@ -8,7 +8,7 @@
from wikitextparser._spans import PF_TL_FINDITER, parse_to_spans


def bytearray_parse_to_spans(bytes_: bytes) -> Dict[str, List[List[int]]]:
def bytearray_parse_to_spans(bytes_: bytes) -> dict[str, list[list[int]]]:
return {
k: [i[:2] for i in v] # no need for match and byte_array
for k, v in parse_to_spans(bytearray(bytes_)).items()
Expand Down
14 changes: 8 additions & 6 deletions wikitextparser/_argument.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
from typing import List, MutableSequence, Optional, Union
from __future__ import annotations

from typing import MutableSequence

from regex import DOTALL, MULTILINE, Match

Expand Down Expand Up @@ -26,11 +28,11 @@ class Argument(SubWikiText):

def __init__(
self,
string: Union[str, MutableSequence[str]],
_type_to_spans: Optional[TypeToSpans] = None,
_span: Optional[List[int]] = None,
_type: Optional[Union[str, int]] = None,
_parent: 'Optional[SubWikiTextWithArgs]' = None,
string: str | MutableSequence[str],
_type_to_spans: TypeToSpans | None = None,
_span: list[int] | None = None,
_type: str | int | None = None,
_parent: SubWikiTextWithArgs | None = None,
):
super().__init__(string, _type_to_spans, _span, _type)
self._parent = _parent or self
Expand Down
8 changes: 5 additions & 3 deletions wikitextparser/_cell.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
from typing import Dict, List, Match, MutableSequence, Union
from __future__ import annotations

from typing import Match, MutableSequence

from regex import DOTALL, VERBOSE

Expand Down Expand Up @@ -144,9 +146,9 @@ class Cell(SubWikiTextWithAttrs):

def __init__(
self,
string: Union[str, MutableSequence[str]],
string: str | MutableSequence[str],
header: bool = False,
_type_to_spans: Dict[str, List[List[int]]] = None,
_type_to_spans: dict[str, list[list[int]]] = None,
_span: int = None,
_type: int = None,
_match: Match = None,
Expand Down
16 changes: 9 additions & 7 deletions wikitextparser/_comment_bold_italic.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
from typing import List, MutableSequence, Optional, Tuple, Union
from __future__ import annotations

from typing import MutableSequence

from regex import DOTALL, MULTILINE, Match

Expand Down Expand Up @@ -30,7 +32,7 @@ def contents(self) -> str:
return s[4:]

@property
def comments(self) -> List['Comment']:
def comments(self) -> list[Comment]:
return []


Expand All @@ -53,7 +55,7 @@ def text(self, s: str):
self[b:e] = s

@property
def _content_span(self) -> Tuple[int, int]:
def _content_span(self) -> tuple[int, int]:
# noinspection PyUnresolvedReferences
return self._match.span(1)

Expand All @@ -71,10 +73,10 @@ class Italic(BoldItalic):

def __init__(
self,
string: Union[str, MutableSequence[str]],
_type_to_spans: Optional[TypeToSpans] = None,
_span: Optional[List[int]] = None,
_type: Optional[Union[str, int]] = None,
string: str | MutableSequence[str],
_type_to_spans: TypeToSpans | None = None,
_span: list[int] | None = None,
_type: str | int | None = None,
end_token: bool = True,
):
"""Initialize the Italic object.
Expand Down
6 changes: 3 additions & 3 deletions wikitextparser/_externallink.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from typing import List, Optional
from __future__ import annotations

from ._wikitext import BRACKET_EXTERNAL_LINK_URL, IGNORECASE, SubWikiText, rc

Expand Down Expand Up @@ -28,7 +28,7 @@ def url(self, newurl: str) -> None:
self[0 : len(self.url)] = newurl

@property
def text(self) -> Optional[str]:
def text(self) -> str | None:
"""The text part (the part after the url).
getter: Return None if this is a bare link or has no associated text.
Expand Down Expand Up @@ -74,5 +74,5 @@ def in_brackets(self) -> bool:
return self(0) == '['

@property
def external_links(self) -> List['ExternalLink']:
def external_links(self) -> list[ExternalLink]:
return []
8 changes: 4 additions & 4 deletions wikitextparser/_parameter.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from typing import List, Optional, Tuple
from __future__ import annotations

from ._wikitext import WS, SubWikiText

Expand Down Expand Up @@ -35,7 +35,7 @@ def pipe(self) -> str:
return '|' if self._shadow.find(124) != -1 else ''

@property
def default(self) -> Optional[str]:
def default(self) -> str | None:
"""The default value of current parameter.
getter: Return None if there is no default.
Expand Down Expand Up @@ -100,9 +100,9 @@ def append_default(self, new_default_name: str) -> None:
] = '{{{' + new_default_name + '|' + innermost_default + '}}}'

@property
def parameters(self) -> List['Parameter']:
def parameters(self) -> list[Parameter]:
return super().parameters[1:]

@property
def _content_span(self) -> Tuple[int, int]:
def _content_span(self) -> tuple[int, int]:
return 3, -3
14 changes: 8 additions & 6 deletions wikitextparser/_parser_function.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
from __future__ import annotations

from bisect import insort
from typing import Iterable, List, Tuple, Union
from typing import Iterable

from ._argument import Argument
from ._wikilist import WikiList
Expand All @@ -19,7 +21,7 @@ class SubWikiTextWithArgs(SubWikiText):
_first_arg_sep = 0

@property
def _content_span(self) -> Tuple[int, int]:
def _content_span(self) -> tuple[int, int]:
return 2, -2

@property
Expand All @@ -32,7 +34,7 @@ def nesting_level(self) -> int:
return self._nesting_level(('Template', 'ParserFunction'))

@property
def arguments(self) -> List[Argument]:
def arguments(self) -> list[Argument]:
"""Parse template content. Create self.name and self.arguments."""
shadow = self._shadow
split_spans = self._name_args_matcher(shadow, 2, -2).spans('arg')
Expand Down Expand Up @@ -65,8 +67,8 @@ def arguments(self) -> List[Argument]:
return arguments

def get_lists(
self, pattern: Union[str, Iterable[str]] = (r'\#', r'\*', '[:;]')
) -> List[WikiList]:
self, pattern: str | Iterable[str] = (r'\#', r'\*', '[:;]')
) -> list[WikiList]:
"""Return the lists in all arguments.
For performance reasons it is usually preferred to get a specific
Expand Down Expand Up @@ -103,5 +105,5 @@ class ParserFunction(SubWikiTextWithArgs):
_first_arg_sep = 58

@property
def parser_functions(self) -> List['ParserFunction']:
def parser_functions(self) -> list[ParserFunction]:
return super().parser_functions[1:]
4 changes: 2 additions & 2 deletions wikitextparser/_section.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from typing import Optional
from __future__ import annotations

from ._wikitext import SubWikiText, rc

Expand Down Expand Up @@ -50,7 +50,7 @@ def level(self, value: int) -> None:
del self[m.end(2) : m.end(2) + level_diff]

@property
def title(self) -> Optional[str]:
def title(self) -> str | None:
"""The title of this section.
getter: Return the title or None for lead sections or sections that
Expand Down
8 changes: 5 additions & 3 deletions wikitextparser/_spans.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
"""Define the functions required for parsing wikitext into spans."""

from __future__ import annotations

from functools import partial
from typing import Callable, Dict, List, Optional, Union
from typing import Callable, Dict, List, Union

from regex import DOTALL, IGNORECASE, REVERSE, Match, compile as rc

Expand Down Expand Up @@ -325,7 +327,7 @@ def extract_tag_extensions(
def _parse_sub_spans(
byte_array: bytearray,
start: int,
end: Optional[int],
end: int | None,
pms_append: Callable,
pfs_append: Callable,
tls_append: Callable,
Expand All @@ -340,7 +342,7 @@ def _parse_sub_spans(
byte_array[ms:me] = byte_array[ms:me].translate(BRACKETS)
while True:
while True:
match: Optional[Match] = None
match: Match | None = None
for match in WIKILINK_PARAM_FINDITER(byte_array, start, end):
ms, me = match.span()
if match[1] is None:
Expand Down
24 changes: 13 additions & 11 deletions wikitextparser/_table.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
from __future__ import annotations

from bisect import insort_right
from collections.abc import Mapping
from typing import Any, Dict, List, Optional, Tuple, TypeVar, Union
from typing import Any, TypeVar

from regex import DOTALL, VERBOSE

Expand Down Expand Up @@ -86,7 +88,7 @@ def _table_shadow(self) -> bytearray:
return shadow

@property
def _match_table(self) -> List[List[Any]]:
def _match_table(self) -> list[list[Any]]:
"""Return match_table."""
table_shadow = self._table_shadow
# Remove table-start and table-end marks.
Expand Down Expand Up @@ -141,7 +143,7 @@ def data(
strip: bool = True,
row: int = None,
column: int = None,
) -> Union[List[List[str]], List[str], str]:
) -> list[list[str]] | list[str] | str:
"""Return a list containing lists of row values.
:param span: If true, calculate rows according to rowspans and colspans
Expand Down Expand Up @@ -209,7 +211,7 @@ def cells(
row: int = None,
column: int = None,
span: bool = True,
) -> Union[List[List[Cell]], List[Cell], Cell]:
) -> list[list[Cell]] | list[Cell] | Cell:
"""Return a list of lists containing Cell objects.
:param span: If is True, rearrange the result according to colspan and
Expand Down Expand Up @@ -283,7 +285,7 @@ def cells(
return table_cells[row][column]

@property
def caption(self) -> Optional[str]:
def caption(self) -> str | None:
"""Caption of the table. Support get and set."""
m = CAPTION_MATCH(self._shadow)
if m:
Expand Down Expand Up @@ -317,7 +319,7 @@ def _attrs_match(self) -> Any:
return attrs_match

@property
def caption_attrs(self) -> Optional[str]:
def caption_attrs(self) -> str | None:
"""Caption attributes. Support get and set operations."""
m = CAPTION_MATCH(self._shadow)
if m:
Expand All @@ -339,7 +341,7 @@ def caption_attrs(self, attrs: str) -> None:
self[m.end('preattrs') : end] = attrs

@property
def row_attrs(self) -> List[dict]:
def row_attrs(self) -> list[dict]:
"""Row attributes.
Use the setter of this property to set attributes for all rows.
Expand All @@ -363,7 +365,7 @@ def row_attrs(self) -> List[dict]:
return attrs

@row_attrs.setter
def row_attrs(self, attrs: List[Mapping]):
def row_attrs(self, attrs: list[Mapping]):
for row_match, attrs_dict in reversed(
[*zip(FIND_ROWS(self._table_shadow), attrs)]
):
Expand All @@ -381,8 +383,8 @@ def row_attrs(self, attrs: List[Mapping]):


def _apply_attr_spans(
table_attrs: List[List[Dict[str, str]]], table_data: List[List[T]]
) -> List[List[T]]:
table_attrs: list[list[dict[str, str]]], table_data: list[list[T]]
) -> list[list[T]]:
"""Apply row and column spans and return table_data."""
# The following code is based on the table forming algorithm described
# at http://www.w3.org/TR/html5/tabular-data.html#processing-model-1
Expand All @@ -399,7 +401,7 @@ def _apply_attr_spans(
# if not table_data:
# return table_data
# 11
downward_growing_cells: List[Tuple[Optional[T], int, int]] = []
downward_growing_cells: list[tuple[T | None, int, int]] = []
# 13, 18
# Algorithm for processing rows
for attrs_row, row in zip(table_attrs, table_data):
Expand Down
14 changes: 8 additions & 6 deletions wikitextparser/_tag.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,9 @@
* https://www.mediawiki.org/wiki/HTML_restriction
"""

from typing import Any, Dict, List, Optional, Tuple
from __future__ import annotations

from typing import Any

from regex import DOTALL, VERBOSE

Expand Down Expand Up @@ -55,7 +57,7 @@ class SubWikiTextWithAttrs(SubWikiText):
__slots__ = '_attrs_match'

@property
def attrs(self) -> Dict[str, str]:
def attrs(self) -> dict[str, str]:
"""Return self attributes as a dictionary."""
spans = self._attrs_match.spans
string = self.string
Expand All @@ -73,7 +75,7 @@ def has_attr(self, attr_name: str) -> bool:
string[s:e] for s, e in self._attrs_match.spans('attr_name')
)

def get_attr(self, attr_name: str) -> Optional[str]:
def get_attr(self, attr_name: str) -> str | None:
"""Return the value of the last attribute with the given name.
Return None if the attr_name does not exist in self.
Expand Down Expand Up @@ -163,7 +165,7 @@ def name(self, name: str) -> None:
self[start:end] = name

@property
def contents(self) -> Optional[str]:
def contents(self) -> str | None:
"""Tag contents. Support both get and set operations.
setter:
Expand Down Expand Up @@ -210,10 +212,10 @@ def parsed_contents(self) -> SubWikiText:
def _extension_tags(self):
return super()._extension_tags[1:]

def get_tags(self, name=None) -> List['Tag']:
def get_tags(self, name=None) -> list[Tag]:
return super().get_tags(name)[1:]

@property
def _content_span(self) -> Tuple[int, int]:
def _content_span(self) -> tuple[int, int]:
s = self.string
return s.find('>') + 1, s.rfind('<')
Loading

0 comments on commit 78c96fb

Please sign in to comment.