Skip to content

Code clean-up #860

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Nov 25, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

## Version 5.3
- Python 3.11 support added
- Removed undocumented, unused `neo4j.data.map_type`
- Query strings are now typed `LiteralString` instead of `str` to help mitigate
accidental Cypher injections. There are rare use-cases where a computed
string is necessary. Please use `# type: ignore`, or `typing.cast` to
Expand Down
10 changes: 5 additions & 5 deletions neo4j/_async/bookmark_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,9 +29,9 @@
)


T_BmSupplier = t.Callable[[t.Optional[str]],
t.Union[Bookmarks, t.Awaitable[Bookmarks]]]
T_BmConsumer = t.Callable[[str, Bookmarks], t.Union[None, t.Awaitable[None]]]
TBmSupplier = t.Callable[[t.Optional[str]],
t.Union[Bookmarks, t.Awaitable[Bookmarks]]]
TBmConsumer = t.Callable[[str, Bookmarks], t.Union[None, t.Awaitable[None]]]


def _bookmarks_to_set(
Expand All @@ -47,8 +47,8 @@ def __init__(
self,
initial_bookmarks: t.Optional[t.Mapping[str, t.Union[Bookmarks,
t.Iterable[str]]]] = None,
bookmarks_supplier: t.Optional[T_BmSupplier] = None,
bookmarks_consumer: t.Optional[T_BmConsumer] = None
bookmarks_supplier: t.Optional[TBmSupplier] = None,
bookmarks_consumer: t.Optional[TBmConsumer] = None
) -> None:
super().__init__()
self._bookmarks_supplier = bookmarks_supplier
Expand Down
18 changes: 9 additions & 9 deletions neo4j/_async/driver.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,8 +68,8 @@
)
from .bookmark_manager import (
AsyncNeo4jBookmarkManager,
T_BmConsumer as _T_BmConsumer,
T_BmSupplier as _T_BmSupplier,
TBmConsumer as _TBmConsumer,
TBmSupplier as _TBmSupplier,
)
from .work import AsyncSession

Expand Down Expand Up @@ -137,7 +137,7 @@ def driver(cls, uri, *, auth=None, **config) -> AsyncDriver:
TRUST_ALL_CERTIFICATES,
TRUST_SYSTEM_CA_SIGNED_CERTIFICATES
):
from neo4j.exceptions import ConfigurationError
from ..exceptions import ConfigurationError
raise ConfigurationError(
"The config setting `trust` values are {!r}"
.format(
Expand All @@ -164,7 +164,7 @@ def driver(cls, uri, *, auth=None, **config) -> AsyncDriver:
or "trust" in config.keys()
or "trusted_certificates" in config.keys()
or "ssl_context" in config.keys())):
from neo4j.exceptions import ConfigurationError
from ..exceptions import ConfigurationError

# TODO: 6.0 remove "trust" from error message
raise ConfigurationError(
Expand Down Expand Up @@ -222,8 +222,8 @@ def bookmark_manager(
cls,
initial_bookmarks: t.Optional[t.Mapping[str, t.Union[Bookmarks,
t.Iterable[str]]]] = None,
bookmarks_supplier: t.Optional[_T_BmSupplier] = None,
bookmarks_consumer: t.Optional[_T_BmConsumer] = None
bookmarks_supplier: t.Optional[_TBmSupplier] = None,
bookmarks_consumer: t.Optional[_TBmConsumer] = None
) -> AsyncBookmarkManager:
"""Create a :class:`.AsyncBookmarkManager` with default implementation.

Expand Down Expand Up @@ -306,23 +306,23 @@ def bolt_driver(cls, target, *, auth=None, **config):
try:
return AsyncBoltDriver.open(target, auth=auth, **config)
except (BoltHandshakeError, BoltSecurityError) as error:
from neo4j.exceptions import ServiceUnavailable
from ..exceptions import ServiceUnavailable
raise ServiceUnavailable(str(error)) from error

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

try:
return AsyncNeo4jDriver.open(*targets, auth=auth, routing_context=routing_context, **config)
except (BoltHandshakeError, BoltSecurityError) as error:
from neo4j.exceptions import ServiceUnavailable
from ..exceptions import ServiceUnavailable
raise ServiceUnavailable(str(error)) from error


Expand Down
3 changes: 1 addition & 2 deletions neo4j/_async/io/_bolt.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@

import abc
import asyncio
import socket
from collections import deque
from logging import getLogger
from time import perf_counter
Expand Down Expand Up @@ -139,7 +138,7 @@ def __init__(self, unresolved_address, sock, max_connection_lifetime, *,
if not auth:
self.auth_dict = {}
elif isinstance(auth, tuple) and 2 <= len(auth) <= 3:
from neo4j import Auth
from ...api import Auth
self.auth_dict = vars(Auth("basic", *auth))
else:
try:
Expand Down
4 changes: 2 additions & 2 deletions neo4j/_async/io/_pool.py
Original file line number Diff line number Diff line change
Expand Up @@ -698,7 +698,7 @@ async def ensure_routing_table_is_fresh(

:returns: `True` if an update was required, `False` otherwise.
"""
from neo4j.api import READ_ACCESS
from ...api import READ_ACCESS
async with self.refresh_lock:
for database_ in list(self.routing_tables.keys()):
# Remove unused databases in the routing table
Expand Down Expand Up @@ -766,7 +766,7 @@ async def acquire(
.format(timeout))


from neo4j.api import check_access_mode
from ...api import check_access_mode
access_mode = check_access_mode(access_mode)
# await self.ensure_routing_table_is_fresh(
# access_mode=access_mode, database=database, imp_user=None,
Expand Down
8 changes: 4 additions & 4 deletions neo4j/_async/work/result.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@


_T = t.TypeVar("_T")
_T_ResultKey = t.Union[int, str]
_TResultKey = t.Union[int, str]


_RESULT_OUT_OF_SCOPE_ERROR = (
Expand Down Expand Up @@ -534,7 +534,7 @@ async def graph(self) -> Graph:
return self._hydration_scope.get_graph()

async def value(
self, key: _T_ResultKey = 0, default: t.Optional[object] = None
self, key: _TResultKey = 0, default: t.Optional[object] = None
) -> t.List[t.Any]:
"""Return the remainder of the result as a list of values.

Expand All @@ -555,7 +555,7 @@ async def value(
return [record.value(key, default) async for record in self]

async def values(
self, *keys: _T_ResultKey
self, *keys: _TResultKey
) -> t.List[t.List[t.Any]]:
"""Return the remainder of the result as a list of values lists.

Expand All @@ -574,7 +574,7 @@ async def values(
"""
return [record.values(*keys) async for record in self]

async def data(self, *keys: _T_ResultKey) -> t.List[t.Dict[str, t.Any]]:
async def data(self, *keys: _TResultKey) -> t.List[t.Dict[str, t.Any]]:
"""Return the remainder of the result as a list of dictionaries.

This function provides a convenient but opinionated way to obtain the
Expand Down
2 changes: 1 addition & 1 deletion neo4j/_async_compat/concurrency.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@
if t.TYPE_CHECKING:
import typing_extensions as te

from neo4j._async_compat.shims import wait_for
from .shims import wait_for


__all__ = [
Expand Down
14 changes: 7 additions & 7 deletions neo4j/_async_compat/network/_bolt_socket.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,13 +39,6 @@
SSLSocket,
)


if t.TYPE_CHECKING:
import typing_extensions as te

from ..._async.io import AsyncBolt
from ..._sync.io import Bolt

from ... import addressing
from ..._deadline import Deadline
from ..._exceptions import (
Expand All @@ -65,6 +58,13 @@
)


if t.TYPE_CHECKING:
import typing_extensions as te

from ..._async.io import AsyncBolt
from ..._sync.io import Bolt


log = logging.getLogger("neo4j")


Expand Down
44 changes: 22 additions & 22 deletions neo4j/_data.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@


_T = t.TypeVar("_T")
_T_K = t.Union[int, str]
_K = t.Union[int, str]


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

def __getitem__( # type: ignore[override]
self, key: t.Union[_T_K, slice]
self, key: t.Union[_K, slice]
) -> t.Any:
if isinstance(key, slice):
keys = self.__keys[key]
Expand Down Expand Up @@ -158,7 +158,7 @@ def get(self, key: str, default: t.Optional[object] = None) -> t.Any:
else:
return default

def index(self, key: _T_K) -> int: # type: ignore[override]
def index(self, key: _K) -> int: # type: ignore[override]
""" Return the index of the given item.

:param key: a key
Expand All @@ -172,13 +172,13 @@ def index(self, key: _T_K) -> int: # type: ignore[override]
elif isinstance(key, str):
try:
return self.__keys.index(key)
except ValueError:
raise KeyError(key)
except ValueError as exc:
raise KeyError(key) from exc
else:
raise TypeError(key)

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

def values(self, *keys: _T_K) -> t.List[t.Any]: # type: ignore[override]
def values(self, *keys: _K) -> t.List[t.Any]: # type: ignore[override]
""" Return the values of the record, optionally filtering to
include only certain values by index or key.

Expand Down Expand Up @@ -242,7 +242,7 @@ def items(self, *keys):
return list((self.__keys[i], self._super_getitem_single(i))
for i in range(len(self)))

def data(self, *keys: _T_K) -> t.Dict[str, t.Any]:
def data(self, *keys: _K) -> t.Dict[str, t.Any]:
""" Return the keys and values of this record as a dictionary,
optionally including only certain values by index or key. Keys
provided in the items that are not in the record will be
Expand Down Expand Up @@ -293,14 +293,14 @@ def transform(self, x):
elif isinstance(x, str):
return x
elif isinstance(x, Sequence):
t = type(x)
return t(map(self.transform, x))
typ = type(x)
return typ(map(self.transform, x))
elif isinstance(x, Set):
t = type(x)
return t(map(self.transform, x))
typ = type(x)
return typ(map(self.transform, x))
elif isinstance(x, Mapping):
t = type(x)
return t((k, self.transform(v)) for k, v in x.items())
typ = type(x)
return typ((k, self.transform(v)) for k, v in x.items())
else:
return x

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

def transform(self, x):
assert isinstance(x, Mapping)
t = type(x)
return t(item
for k, v in x.items()
for item in self._transform(
v, prefix=k.replace("\\", "\\\\").replace(".", "\\.")
).items())
typ = type(x)
return typ(item
for k, v in x.items()
for item in self._transform(
v, prefix=k.replace("\\", "\\\\").replace(".", "\\.")
).items())

def _transform(self, x, prefix):
if isinstance(x, Node):
Expand Down Expand Up @@ -345,8 +345,8 @@ def _transform(self, x, prefix):
).items()
)
elif isinstance(x, Mapping):
t = type(x)
return t(
typ = type(x)
return typ(
item
for k, v in x.items()
for item in self._transform(
Expand Down
8 changes: 4 additions & 4 deletions neo4j/_routing.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ def remove(self, element):
try:
del self._elements[element]
except KeyError:
raise ValueError(element)
raise ValueError(element) from None

def update(self, elements=()):
self._elements.update(dict.fromkeys(elements))
Expand Down Expand Up @@ -97,8 +97,8 @@ def parse_routing_info(cls, *, database, servers, ttl):
readers.extend(addresses)
elif role == "WRITE":
writers.extend(addresses)
except (KeyError, TypeError):
raise ValueError("Cannot parse routing info")
except (KeyError, TypeError) as exc:
raise ValueError("Cannot parse routing info") from exc
else:
return cls(database=database, routers=routers, readers=readers, writers=writers, ttl=ttl)

Expand Down Expand Up @@ -147,7 +147,7 @@ def should_be_purged_from_memory(self):
:returns: Returns true if it is old and not used for a while.
:rtype: bool
"""
from neo4j._conf import RoutingConfig
from ._conf import RoutingConfig
perf_time = perf_counter()
res = self.last_updated_time + self.ttl + RoutingConfig.routing_table_purge_delay <= perf_time
log.debug("[#0000] _: <ROUTING> purge check: "
Expand Down
10 changes: 5 additions & 5 deletions neo4j/_sync/bookmark_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,9 +29,9 @@
)


T_BmSupplier = t.Callable[[t.Optional[str]],
t.Union[Bookmarks, t.Union[Bookmarks]]]
T_BmConsumer = t.Callable[[str, Bookmarks], t.Union[None, t.Union[None]]]
TBmSupplier = t.Callable[[t.Optional[str]],
t.Union[Bookmarks, t.Union[Bookmarks]]]
TBmConsumer = t.Callable[[str, Bookmarks], t.Union[None, t.Union[None]]]


def _bookmarks_to_set(
Expand All @@ -47,8 +47,8 @@ def __init__(
self,
initial_bookmarks: t.Optional[t.Mapping[str, t.Union[Bookmarks,
t.Iterable[str]]]] = None,
bookmarks_supplier: t.Optional[T_BmSupplier] = None,
bookmarks_consumer: t.Optional[T_BmConsumer] = None
bookmarks_supplier: t.Optional[TBmSupplier] = None,
bookmarks_consumer: t.Optional[TBmConsumer] = None
) -> None:
super().__init__()
self._bookmarks_supplier = bookmarks_supplier
Expand Down
Loading