forked from wikimedia/pywikibot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbackports.py
115 lines (92 loc) · 2.78 KB
/
backports.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
"""This module contains backports to support older Python versions."""
#
# (C) Pywikibot team, 2014-2021
#
# Distributed under the terms of the MIT license.
#
import sys
from typing import Any
PYTHON_VERSION = sys.version_info[:3]
# functools.cache
if PYTHON_VERSION >= (3, 9):
from functools import cache # type: ignore[attr-defined]
else:
from functools import lru_cache as _lru_cache
cache = _lru_cache(None)
# context
if PYTHON_VERSION < (3, 7):
class nullcontext: # noqa: N801
"""Dummy context manager for Python 3.5/3.6 that does nothing."""
def __init__(self, result: Any = None) -> None: # noqa: D107
self.result = result
def __enter__(self) -> Any:
return self.result
def __exit__(self, *args: Any) -> None:
pass
else:
from contextlib import nullcontext # type: ignore[misc]
# queue
if PYTHON_VERSION < (3, 7):
from queue import Queue as SimpleQueue
else:
from queue import SimpleQueue # type: ignore[misc]
# typing
if PYTHON_VERSION < (3, 9):
from typing import DefaultDict # type: ignore[misc]
else:
from collections import ( # type: ignore[misc] # noqa: N812
defaultdict as DefaultDict
)
if PYTHON_VERSION < (3, 7, 2):
from typing import Dict as OrderedDict
elif PYTHON_VERSION < (3, 9):
from typing import OrderedDict
else:
from collections import OrderedDict
if PYTHON_VERSION < (3, 9):
from typing import (
Dict,
FrozenSet,
Iterable,
Iterator,
List,
Mapping,
Match,
Pattern,
Sequence,
Set,
Tuple,
Type,
)
else:
from collections.abc import Iterable, Iterator, Mapping, Sequence
from re import Match, Pattern
Dict = dict # type: ignore[misc]
FrozenSet = frozenset # type: ignore[misc]
List = list # type: ignore[misc]
Set = set # type: ignore[misc]
Tuple = tuple # type: ignore[assignment]
Type = type
if PYTHON_VERSION < (3, 9, 2):
from typing import Callable
else:
from collections.abc import Callable
# PEP 616 string methods
if PYTHON_VERSION >= (3, 9):
removeprefix = str.removeprefix # type: ignore[attr-defined]
removesuffix = str.removesuffix # type: ignore[attr-defined]
else:
def removeprefix(string: str, prefix: str) -> str:
"""Remove prefix from a string or return a copy otherwise.
.. versionadded:: 5.4
"""
if string.startswith(prefix):
return string[len(prefix):]
return string
def removesuffix(string: str, suffix: str) -> str:
"""Remove prefix from a string or return a copy otherwise.
.. versionadded:: 5.4
"""
if string.endswith(suffix):
return string[:-len(suffix)]
return string