Skip to content

Commit 582adc2

Browse files
committed
Merge branch 'release/3.0.0'
2 parents 4d5905f + 928b29d commit 582adc2

17 files changed

Lines changed: 287 additions & 157 deletions

File tree

‎.github/workflows/lint.yml‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ jobs:
1313
strategy:
1414
fail-fast: false
1515
matrix:
16-
python-version: ['3.8', '3.8', '3.10', '3.11']
16+
python-version: ['3.9', '3.10', '3.11', '3.12']
1717

1818
steps:
1919
- uses: actions/checkout@v4

‎.github/workflows/python-package.yml‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ jobs:
1616
strategy:
1717
fail-fast: false
1818
matrix:
19-
python-version: ['3.8', '3.9', '3.10', '3.11']
19+
python-version: ['3.9', '3.10', '3.11', '3.12']
2020
os: ['macos-latest', 'windows-latest']
2121

2222
steps:
@@ -41,7 +41,7 @@ jobs:
4141
strategy:
4242
fail-fast: false
4343
matrix:
44-
python-version: ['3.8', '3.9', '3.10', '3.11']
44+
python-version: ['3.9', '3.10', '3.11', '3.12']
4545

4646
steps:
4747
- uses: actions/checkout@v4

‎.github/workflows/stale.yml‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,6 @@ jobs:
1212
- uses: actions/stale@v8
1313
with:
1414
days-before-stale: 30
15+
days-before-pr-stale: -1
1516
exempt-issue-labels: in-progress,help-wanted,pinned,security,enhancement
1617
exempt-all-pr-assignees: true
17-

‎docs/conf.py‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -350,4 +350,6 @@
350350

351351

352352
# Example configuration for intersphinx: refer to the Python standard library.
353-
intersphinx_mapping = {'http://docs.python.org/3/': None}
353+
intersphinx_mapping = dict(
354+
python=('http://docs.python.org/3/', None),
355+
)

‎portalocker/__about__.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
__package_name__ = 'portalocker'
22
__author__ = 'Rick van Hattem'
33
__email__ = '[email protected]'
4-
__version__ = '2.10.1'
4+
__version__ = '3.0.0'
55
__description__ = '''Wraps the portalocker recipe for easy usage'''
66
__url__ = 'https://github.com/WoLpH/portalocker'

‎portalocker/__init__.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@
2020
#: Current author's email address
2121
__email__ = __about__.__email__
2222
#: Version number
23-
__version__ = '2.10.1'
23+
__version__ = '3.0.0'
2424
#: Package description for Pypi
2525
__description__ = __about__.__description__
2626
#: Package homepage

‎portalocker/__main__.py‎

Lines changed: 18 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
from __future__ import annotations
2+
13
import argparse
24
import logging
35
import os
@@ -25,7 +27,7 @@
2527
logger = logging.getLogger(__name__)
2628

2729

28-
def main(argv=None):
30+
def main(argv: typing.Sequence[str] | None = None) -> None:
2931
parser = argparse.ArgumentParser()
3032

3133
subparsers = parser.add_subparsers(required=True)
@@ -46,15 +48,21 @@ def main(argv=None):
4648
args.func(args)
4749

4850

49-
def _read_file(path: pathlib.Path, seen_files: typing.Set[pathlib.Path]):
51+
def _read_file(
52+
path: pathlib.Path,
53+
seen_files: set[pathlib.Path],
54+
) -> typing.Iterator[str]:
5055
if path in seen_files:
5156
return
5257

53-
names = set()
58+
names: set[str] = set()
5459
seen_files.add(path)
5560
paren = False
5661
from_ = None
5762
for line in path.open():
63+
if '__future__' in line:
64+
continue
65+
5866
if paren:
5967
if ')' in line:
6068
line = line.split(')', 1)[1]
@@ -82,28 +90,31 @@ def _read_file(path: pathlib.Path, seen_files: typing.Set[pathlib.Path]):
8290
yield _clean_line(line, names)
8391

8492

85-
def _clean_line(line, names):
93+
def _clean_line(line: str, names: set[str]):
8694
# Replace `some_import.spam` with `spam`
8795
if names:
8896
joined_names = '|'.join(names)
89-
line = re.sub(fr'\b({joined_names})\.', '', line)
97+
line = re.sub(rf'\b({joined_names})\.', '', line)
9098

9199
# Replace useless assignments (e.g. `spam = spam`)
92100
return _USELESS_ASSIGNMENT_RE.sub('', line)
93101

94102

95-
def combine(args):
103+
def combine(args: argparse.Namespace):
96104
output_file = args.output_file
97105
pathlib.Path(output_file.name).parent.mkdir(parents=True, exist_ok=True)
98106

107+
# We're handling this separately because it has to be the first import.
108+
output_file.write('from __future__ import annotations\n')
109+
99110
output_file.write(
100111
_TEXT_TEMPLATE.format((base_path / 'README.rst').read_text()),
101112
)
102113
output_file.write(
103114
_TEXT_TEMPLATE.format((base_path / 'LICENSE').read_text()),
104115
)
105116

106-
seen_files: typing.Set[pathlib.Path] = set()
117+
seen_files: set[pathlib.Path] = set()
107118
for line in _read_file(src_path / '__init__.py', seen_files):
108119
output_file.write(line)
109120

‎portalocker/exceptions.py‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
import typing
22

3+
from portalocker import types
4+
35

46
class BaseLockException(Exception): # noqa: N818
57
# Error codes:
@@ -8,7 +10,7 @@ class BaseLockException(Exception): # noqa: N818
810
def __init__(
911
self,
1012
*args: typing.Any,
11-
fh: typing.Union[typing.IO, None, int] = None,
13+
fh: typing.Union[types.IO, None, int] = None,
1214
**kwargs: typing.Any,
1315
) -> None:
1416
self.fh = fh

‎portalocker/portalocker.py‎

Lines changed: 13 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,9 @@
1+
from __future__ import annotations
2+
13
import os
24
import typing
35

4-
from . import constants, exceptions
6+
from . import constants, exceptions, types
57

68
# Alias for readability. Due to import recursion issues we cannot do:
79
# from .constants import LockFlags
@@ -12,9 +14,7 @@ class HasFileno(typing.Protocol):
1214
def fileno(self) -> int: ...
1315

1416

15-
LOCKER: typing.Optional[typing.Callable[
16-
[typing.Union[int, HasFileno], int], typing.Any]] = None
17-
17+
LOCKER: typing.Callable[[int | HasFileno, int], typing.Any] | None = None
1818

1919
if os.name == 'nt': # pragma: no cover
2020
import msvcrt
@@ -26,7 +26,7 @@ def fileno(self) -> int: ...
2626

2727
__overlapped = pywintypes.OVERLAPPED()
2828

29-
def lock(file_: typing.Union[typing.IO, int], flags: LockFlags):
29+
def lock(file_: typing.IO | int, flags: LockFlags):
3030
# Windows locking does not support locking through `fh.fileno()` so
3131
# we cast it to make mypy and pyright happy
3232
file_ = typing.cast(typing.IO, file_)
@@ -100,9 +100,9 @@ def unlock(file_: typing.IO):
100100
# The locking implementation.
101101
# Expected values are either fcntl.flock() or fcntl.lockf(),
102102
# but any callable that matches the syntax will be accepted.
103-
LOCKER = fcntl.flock
103+
LOCKER = fcntl.flock # pyright: ignore[reportConstantRedefinition]
104104

105-
def lock(file_: typing.Union[typing.IO, int], flags: LockFlags):
105+
def lock(file: int | types.IO, flags: LockFlags): # type: ignore[misc]
106106
assert LOCKER is not None, 'We need a locking function in `LOCKER` '
107107
# Locking with NON_BLOCKING without EXCLUSIVE or SHARED enabled
108108
# results in an error
@@ -115,7 +115,7 @@ def lock(file_: typing.Union[typing.IO, int], flags: LockFlags):
115115
)
116116

117117
try:
118-
LOCKER(file_, flags)
118+
LOCKER(file, flags)
119119
except OSError as exc_value:
120120
# Python can use one of several different exception classes to
121121
# represent timeout (most likely is BlockingIOError and IOError),
@@ -130,25 +130,25 @@ def lock(file_: typing.Union[typing.IO, int], flags: LockFlags):
130130
# again (if it wants to).
131131
raise exceptions.AlreadyLocked(
132132
exc_value,
133-
fh=file_,
133+
fh=file,
134134
) from exc_value
135135
else:
136136
# Something else went wrong; don't wrap this so we stop
137137
# immediately.
138138
raise exceptions.LockException(
139139
exc_value,
140-
fh=file_,
140+
fh=file,
141141
) from exc_value
142142
except EOFError as exc_value:
143143
# On NFS filesystems, flock can raise an EOFError
144144
raise exceptions.LockException(
145145
exc_value,
146-
fh=file_,
146+
fh=file,
147147
) from exc_value
148148

149-
def unlock(file_: typing.IO):
149+
def unlock(file: types.IO): # type: ignore[misc]
150150
assert LOCKER is not None, 'We need a locking function in `LOCKER` '
151-
LOCKER(file_.fileno(), LockFlags.UNBLOCK)
151+
LOCKER(file.fileno(), LockFlags.UNBLOCK)
152152

153153
else: # pragma: no cover
154154
raise RuntimeError('PortaLocker only defined for nt and posix platforms')

‎portalocker/redis.py‎

Lines changed: 37 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,14 @@
1+
# pyright: reportUnknownMemberType=false
2+
from __future__ import annotations
3+
14
import _thread
25
import json
36
import logging
47
import random
58
import time
69
import typing
710

8-
from redis import client
11+
import redis
912

1013
from . import exceptions, utils
1114

@@ -15,8 +18,8 @@
1518
DEFAULT_THREAD_SLEEP_TIME = 0.1
1619

1720

18-
class PubSubWorkerThread(client.PubSubWorkerThread): # type: ignore
19-
def run(self):
21+
class PubSubWorkerThread(redis.client.PubSubWorkerThread): # type: ignore
22+
def run(self) -> None:
2023
try:
2124
super().run()
2225
except Exception: # pragma: no cover
@@ -61,28 +64,29 @@ class RedisLock(utils.LockBase):
6164
6265
'''
6366

64-
redis_kwargs: typing.Dict[str, typing.Any]
65-
thread: typing.Optional[PubSubWorkerThread]
67+
redis_kwargs: dict[str, typing.Any]
68+
thread: PubSubWorkerThread | None
6669
channel: str
6770
timeout: float
68-
connection: typing.Optional[client.Redis]
69-
pubsub: typing.Optional[client.PubSub] = None
71+
connection: redis.client.Redis[str] | None
72+
pubsub: redis.client.PubSub | None = None
7073
close_connection: bool
7174

72-
DEFAULT_REDIS_KWARGS: typing.ClassVar[typing.Dict[str, typing.Any]] = dict(
75+
DEFAULT_REDIS_KWARGS: typing.ClassVar[dict[str, typing.Any]] = dict(
7376
health_check_interval=10,
77+
decode_responses=True,
7478
)
7579

7680
def __init__(
7781
self,
7882
channel: str,
79-
connection: typing.Optional[client.Redis] = None,
80-
timeout: typing.Optional[float] = None,
81-
check_interval: typing.Optional[float] = None,
82-
fail_when_locked: typing.Optional[bool] = False,
83+
connection: redis.client.Redis[str] | None = None,
84+
timeout: float | None = None,
85+
check_interval: float | None = None,
86+
fail_when_locked: bool | None = False,
8387
thread_sleep_time: float = DEFAULT_THREAD_SLEEP_TIME,
8488
unavailable_timeout: float = DEFAULT_UNAVAILABLE_TIMEOUT,
85-
redis_kwargs: typing.Optional[typing.Dict] = None,
89+
redis_kwargs: dict[str, typing.Any] | None = None,
8690
):
8791
# We don't want to close connections given as an argument
8892
self.close_connection = not connection
@@ -103,18 +107,22 @@ def __init__(
103107
fail_when_locked=fail_when_locked,
104108
)
105109

106-
def get_connection(self) -> client.Redis:
110+
def get_connection(self) -> redis.client.Redis[str]:
107111
if not self.connection:
108-
self.connection = client.Redis(**self.redis_kwargs)
112+
self.connection = redis.client.Redis(**self.redis_kwargs)
109113

110114
return self.connection
111115

112-
def channel_handler(self, message):
116+
def channel_handler(self, message: dict[str, str]) -> None:
113117
if message.get('type') != 'message': # pragma: no cover
114118
return
115119

120+
raw_data = message.get('data')
121+
if not raw_data:
122+
return
123+
116124
try:
117-
data = json.loads(message.get('data'))
125+
data = json.loads(raw_data)
118126
except TypeError: # pragma: no cover
119127
logger.debug('TypeError while parsing: %r', message)
120128
return
@@ -128,10 +136,10 @@ def client_name(self):
128136

129137
def acquire( # type: ignore[override]
130138
self,
131-
timeout: typing.Optional[float] = None,
132-
check_interval: typing.Optional[float] = None,
133-
fail_when_locked: typing.Optional[bool] = None,
134-
) -> 'RedisLock':
139+
timeout: float | None = None,
140+
check_interval: float | None = None,
141+
fail_when_locked: bool | None = None,
142+
) -> RedisLock:
135143
timeout = utils.coalesce(timeout, self.timeout, 0.0)
136144
check_interval = utils.coalesce(
137145
check_interval,
@@ -189,7 +197,11 @@ def acquire( # type: ignore[override]
189197

190198
raise exceptions.AlreadyLocked(exceptions)
191199

192-
def check_or_kill_lock(self, connection, timeout):
200+
def check_or_kill_lock(
201+
self,
202+
connection: redis.client.Redis[str],
203+
timeout: float,
204+
):
193205
# Random channel name to get messages back from the lock
194206
response_channel = f'{self.channel}-{random.random()}'
195207

@@ -217,7 +229,9 @@ def check_or_kill_lock(self, connection, timeout):
217229
for client_ in connection.client_list('pubsub'): # pragma: no cover
218230
if client_.get('name') == self.client_name:
219231
logger.warning('Killing unavailable redis client: %r', client_)
220-
connection.client_kill_filter(client_.get('id'))
232+
connection.client_kill_filter( # pyright: ignore
233+
client_.get('id'),
234+
)
221235
return None
222236

223237
def release(self):

0 commit comments

Comments
 (0)