Skip to content

Commit fa81522

Browse files
authored
Code clean-up (#860)
* type alias and variable naming * use relative imports * specify error causes when rewriting (`raise ... from ...`)
1 parent 4a7549e commit fa81522

21 files changed

+104
-115
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
## Version 5.3
44
- Python 3.11 support added
5+
- Removed undocumented, unused `neo4j.data.map_type`
56
- Query strings are now typed `LiteralString` instead of `str` to help mitigate
67
accidental Cypher injections. There are rare use-cases where a computed
78
string is necessary. Please use `# type: ignore`, or `typing.cast` to

neo4j/_async/bookmark_manager.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -29,9 +29,9 @@
2929
)
3030

3131

32-
T_BmSupplier = t.Callable[[t.Optional[str]],
33-
t.Union[Bookmarks, t.Awaitable[Bookmarks]]]
34-
T_BmConsumer = t.Callable[[str, Bookmarks], t.Union[None, t.Awaitable[None]]]
32+
TBmSupplier = t.Callable[[t.Optional[str]],
33+
t.Union[Bookmarks, t.Awaitable[Bookmarks]]]
34+
TBmConsumer = t.Callable[[str, Bookmarks], t.Union[None, t.Awaitable[None]]]
3535

3636

3737
def _bookmarks_to_set(
@@ -47,8 +47,8 @@ def __init__(
4747
self,
4848
initial_bookmarks: t.Optional[t.Mapping[str, t.Union[Bookmarks,
4949
t.Iterable[str]]]] = None,
50-
bookmarks_supplier: t.Optional[T_BmSupplier] = None,
51-
bookmarks_consumer: t.Optional[T_BmConsumer] = None
50+
bookmarks_supplier: t.Optional[TBmSupplier] = None,
51+
bookmarks_consumer: t.Optional[TBmConsumer] = None
5252
) -> None:
5353
super().__init__()
5454
self._bookmarks_supplier = bookmarks_supplier

neo4j/_async/driver.py

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -68,8 +68,8 @@
6868
)
6969
from .bookmark_manager import (
7070
AsyncNeo4jBookmarkManager,
71-
T_BmConsumer as _T_BmConsumer,
72-
T_BmSupplier as _T_BmSupplier,
71+
TBmConsumer as _TBmConsumer,
72+
TBmSupplier as _TBmSupplier,
7373
)
7474
from .work import AsyncSession
7575

@@ -137,7 +137,7 @@ def driver(cls, uri, *, auth=None, **config) -> AsyncDriver:
137137
TRUST_ALL_CERTIFICATES,
138138
TRUST_SYSTEM_CA_SIGNED_CERTIFICATES
139139
):
140-
from neo4j.exceptions import ConfigurationError
140+
from ..exceptions import ConfigurationError
141141
raise ConfigurationError(
142142
"The config setting `trust` values are {!r}"
143143
.format(
@@ -164,7 +164,7 @@ def driver(cls, uri, *, auth=None, **config) -> AsyncDriver:
164164
or "trust" in config.keys()
165165
or "trusted_certificates" in config.keys()
166166
or "ssl_context" in config.keys())):
167-
from neo4j.exceptions import ConfigurationError
167+
from ..exceptions import ConfigurationError
168168

169169
# TODO: 6.0 remove "trust" from error message
170170
raise ConfigurationError(
@@ -222,8 +222,8 @@ def bookmark_manager(
222222
cls,
223223
initial_bookmarks: t.Optional[t.Mapping[str, t.Union[Bookmarks,
224224
t.Iterable[str]]]] = None,
225-
bookmarks_supplier: t.Optional[_T_BmSupplier] = None,
226-
bookmarks_consumer: t.Optional[_T_BmConsumer] = None
225+
bookmarks_supplier: t.Optional[_TBmSupplier] = None,
226+
bookmarks_consumer: t.Optional[_TBmConsumer] = None
227227
) -> AsyncBookmarkManager:
228228
"""Create a :class:`.AsyncBookmarkManager` with default implementation.
229229
@@ -306,23 +306,23 @@ def bolt_driver(cls, target, *, auth=None, **config):
306306
try:
307307
return AsyncBoltDriver.open(target, auth=auth, **config)
308308
except (BoltHandshakeError, BoltSecurityError) as error:
309-
from neo4j.exceptions import ServiceUnavailable
309+
from ..exceptions import ServiceUnavailable
310310
raise ServiceUnavailable(str(error)) from error
311311

312312
@classmethod
313313
def neo4j_driver(cls, *targets, auth=None, routing_context=None, **config):
314314
""" Create a driver for routing-capable Neo4j service access
315315
that uses socket I/O and thread-based concurrency.
316316
"""
317-
from neo4j._exceptions import (
317+
from .._exceptions import (
318318
BoltHandshakeError,
319319
BoltSecurityError,
320320
)
321321

322322
try:
323323
return AsyncNeo4jDriver.open(*targets, auth=auth, routing_context=routing_context, **config)
324324
except (BoltHandshakeError, BoltSecurityError) as error:
325-
from neo4j.exceptions import ServiceUnavailable
325+
from ..exceptions import ServiceUnavailable
326326
raise ServiceUnavailable(str(error)) from error
327327

328328

neo4j/_async/io/_bolt.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,6 @@
2020

2121
import abc
2222
import asyncio
23-
import socket
2423
from collections import deque
2524
from logging import getLogger
2625
from time import perf_counter
@@ -139,7 +138,7 @@ def __init__(self, unresolved_address, sock, max_connection_lifetime, *,
139138
if not auth:
140139
self.auth_dict = {}
141140
elif isinstance(auth, tuple) and 2 <= len(auth) <= 3:
142-
from neo4j import Auth
141+
from ...api import Auth
143142
self.auth_dict = vars(Auth("basic", *auth))
144143
else:
145144
try:

neo4j/_async/io/_pool.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -698,7 +698,7 @@ async def ensure_routing_table_is_fresh(
698698
699699
:returns: `True` if an update was required, `False` otherwise.
700700
"""
701-
from neo4j.api import READ_ACCESS
701+
from ...api import READ_ACCESS
702702
async with self.refresh_lock:
703703
for database_ in list(self.routing_tables.keys()):
704704
# Remove unused databases in the routing table
@@ -766,7 +766,7 @@ async def acquire(
766766
.format(timeout))
767767

768768

769-
from neo4j.api import check_access_mode
769+
from ...api import check_access_mode
770770
access_mode = check_access_mode(access_mode)
771771
# await self.ensure_routing_table_is_fresh(
772772
# access_mode=access_mode, database=database, imp_user=None,

neo4j/_async/work/result.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,7 @@
5454

5555

5656
_T = t.TypeVar("_T")
57-
_T_ResultKey = t.Union[int, str]
57+
_TResultKey = t.Union[int, str]
5858

5959

6060
_RESULT_OUT_OF_SCOPE_ERROR = (
@@ -534,7 +534,7 @@ async def graph(self) -> Graph:
534534
return self._hydration_scope.get_graph()
535535

536536
async def value(
537-
self, key: _T_ResultKey = 0, default: t.Optional[object] = None
537+
self, key: _TResultKey = 0, default: t.Optional[object] = None
538538
) -> t.List[t.Any]:
539539
"""Return the remainder of the result as a list of values.
540540
@@ -555,7 +555,7 @@ async def value(
555555
return [record.value(key, default) async for record in self]
556556

557557
async def values(
558-
self, *keys: _T_ResultKey
558+
self, *keys: _TResultKey
559559
) -> t.List[t.List[t.Any]]:
560560
"""Return the remainder of the result as a list of values lists.
561561
@@ -574,7 +574,7 @@ async def values(
574574
"""
575575
return [record.values(*keys) async for record in self]
576576

577-
async def data(self, *keys: _T_ResultKey) -> t.List[t.Dict[str, t.Any]]:
577+
async def data(self, *keys: _TResultKey) -> t.List[t.Dict[str, t.Any]]:
578578
"""Return the remainder of the result as a list of dictionaries.
579579
580580
This function provides a convenient but opinionated way to obtain the

neo4j/_async_compat/concurrency.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@
2828
if t.TYPE_CHECKING:
2929
import typing_extensions as te
3030

31-
from neo4j._async_compat.shims import wait_for
31+
from .shims import wait_for
3232

3333

3434
__all__ = [

neo4j/_async_compat/network/_bolt_socket.py

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -39,13 +39,6 @@
3939
SSLSocket,
4040
)
4141

42-
43-
if t.TYPE_CHECKING:
44-
import typing_extensions as te
45-
46-
from ..._async.io import AsyncBolt
47-
from ..._sync.io import Bolt
48-
4942
from ... import addressing
5043
from ..._deadline import Deadline
5144
from ..._exceptions import (
@@ -65,6 +58,13 @@
6558
)
6659

6760

61+
if t.TYPE_CHECKING:
62+
import typing_extensions as te
63+
64+
from ..._async.io import AsyncBolt
65+
from ..._sync.io import Bolt
66+
67+
6868
log = logging.getLogger("neo4j")
6969

7070

neo4j/_data.py

Lines changed: 22 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,7 @@
4343

4444

4545
_T = t.TypeVar("_T")
46-
_T_K = t.Union[int, str]
46+
_K = t.Union[int, str]
4747

4848

4949
class Record(tuple, Mapping):
@@ -119,7 +119,7 @@ def __iter__(self) -> t.Iterator[t.Any]:
119119
yield v
120120

121121
def __getitem__( # type: ignore[override]
122-
self, key: t.Union[_T_K, slice]
122+
self, key: t.Union[_K, slice]
123123
) -> t.Any:
124124
if isinstance(key, slice):
125125
keys = self.__keys[key]
@@ -158,7 +158,7 @@ def get(self, key: str, default: t.Optional[object] = None) -> t.Any:
158158
else:
159159
return default
160160

161-
def index(self, key: _T_K) -> int: # type: ignore[override]
161+
def index(self, key: _K) -> int: # type: ignore[override]
162162
""" Return the index of the given item.
163163
164164
:param key: a key
@@ -172,13 +172,13 @@ def index(self, key: _T_K) -> int: # type: ignore[override]
172172
elif isinstance(key, str):
173173
try:
174174
return self.__keys.index(key)
175-
except ValueError:
176-
raise KeyError(key)
175+
except ValueError as exc:
176+
raise KeyError(key) from exc
177177
else:
178178
raise TypeError(key)
179179

180180
def value(
181-
self, key: _T_K = 0, default: t.Optional[object] = None
181+
self, key: _K = 0, default: t.Optional[object] = None
182182
) -> t.Any:
183183
""" Obtain a single value from the record by index or key. If no
184184
index or key is specified, the first value is returned. If the
@@ -203,7 +203,7 @@ def keys(self) -> t.List[str]: # type: ignore[override]
203203
"""
204204
return list(self.__keys)
205205

206-
def values(self, *keys: _T_K) -> t.List[t.Any]: # type: ignore[override]
206+
def values(self, *keys: _K) -> t.List[t.Any]: # type: ignore[override]
207207
""" Return the values of the record, optionally filtering to
208208
include only certain values by index or key.
209209
@@ -242,7 +242,7 @@ def items(self, *keys):
242242
return list((self.__keys[i], self._super_getitem_single(i))
243243
for i in range(len(self)))
244244

245-
def data(self, *keys: _T_K) -> t.Dict[str, t.Any]:
245+
def data(self, *keys: _K) -> t.Dict[str, t.Any]:
246246
""" Return the keys and values of this record as a dictionary,
247247
optionally including only certain values by index or key. Keys
248248
provided in the items that are not in the record will be
@@ -293,14 +293,14 @@ def transform(self, x):
293293
elif isinstance(x, str):
294294
return x
295295
elif isinstance(x, Sequence):
296-
t = type(x)
297-
return t(map(self.transform, x))
296+
typ = type(x)
297+
return typ(map(self.transform, x))
298298
elif isinstance(x, Set):
299-
t = type(x)
300-
return t(map(self.transform, x))
299+
typ = type(x)
300+
return typ(map(self.transform, x))
301301
elif isinstance(x, Mapping):
302-
t = type(x)
303-
return t((k, self.transform(v)) for k, v in x.items())
302+
typ = type(x)
303+
return typ((k, self.transform(v)) for k, v in x.items())
304304
else:
305305
return x
306306

@@ -310,12 +310,12 @@ class RecordTableRowExporter(DataTransformer):
310310

311311
def transform(self, x):
312312
assert isinstance(x, Mapping)
313-
t = type(x)
314-
return t(item
315-
for k, v in x.items()
316-
for item in self._transform(
317-
v, prefix=k.replace("\\", "\\\\").replace(".", "\\.")
318-
).items())
313+
typ = type(x)
314+
return typ(item
315+
for k, v in x.items()
316+
for item in self._transform(
317+
v, prefix=k.replace("\\", "\\\\").replace(".", "\\.")
318+
).items())
319319

320320
def _transform(self, x, prefix):
321321
if isinstance(x, Node):
@@ -345,8 +345,8 @@ def _transform(self, x, prefix):
345345
).items()
346346
)
347347
elif isinstance(x, Mapping):
348-
t = type(x)
349-
return t(
348+
typ = type(x)
349+
return typ(
350350
item
351351
for k, v in x.items()
352352
for item in self._transform(

neo4j/_routing.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -64,7 +64,7 @@ def remove(self, element):
6464
try:
6565
del self._elements[element]
6666
except KeyError:
67-
raise ValueError(element)
67+
raise ValueError(element) from None
6868

6969
def update(self, elements=()):
7070
self._elements.update(dict.fromkeys(elements))
@@ -97,8 +97,8 @@ def parse_routing_info(cls, *, database, servers, ttl):
9797
readers.extend(addresses)
9898
elif role == "WRITE":
9999
writers.extend(addresses)
100-
except (KeyError, TypeError):
101-
raise ValueError("Cannot parse routing info")
100+
except (KeyError, TypeError) as exc:
101+
raise ValueError("Cannot parse routing info") from exc
102102
else:
103103
return cls(database=database, routers=routers, readers=readers, writers=writers, ttl=ttl)
104104

@@ -147,7 +147,7 @@ def should_be_purged_from_memory(self):
147147
:returns: Returns true if it is old and not used for a while.
148148
:rtype: bool
149149
"""
150-
from neo4j._conf import RoutingConfig
150+
from ._conf import RoutingConfig
151151
perf_time = perf_counter()
152152
res = self.last_updated_time + self.ttl + RoutingConfig.routing_table_purge_delay <= perf_time
153153
log.debug("[#0000] _: <ROUTING> purge check: "

0 commit comments

Comments
 (0)