Skip to content

Commit

Permalink
Make code compatible with mypy 0.990 (#854)
Browse files Browse the repository at this point in the history
 * remove implicit optional parameters (PEP 484 received an update)
 * mute metaclass inference limitations of mypy
 * fix mypy rightfully complaining about empty method bodies
 * fixed bug in (deprecated) `session.last_bookmark` that mypy uncovered
  • Loading branch information
robsdedude authored Nov 9, 2022
1 parent b42e7f1 commit 64112ff
Show file tree
Hide file tree
Showing 21 changed files with 109 additions and 84 deletions.
8 changes: 4 additions & 4 deletions neo4j/_async/bookmark_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,10 +45,10 @@ def _bookmarks_to_set(
class AsyncNeo4jBookmarkManager(AsyncBookmarkManager):
def __init__(
self,
initial_bookmarks: t.Mapping[str, t.Union[Bookmarks,
t.Iterable[str]]] = None,
bookmarks_supplier: T_BmSupplier = None,
bookmarks_consumer: T_BmConsumer = None
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
) -> None:
super().__init__()
self._bookmarks_supplier = bookmarks_supplier
Expand Down
10 changes: 6 additions & 4 deletions neo4j/_async/driver.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,8 @@

import ssl



from .._async_compat.util import AsyncUtil
from .._conf import (
Config,
Expand Down Expand Up @@ -218,10 +220,10 @@ def driver(cls, uri, *, auth=None, **config) -> AsyncDriver:
)
def bookmark_manager(
cls,
initial_bookmarks: t.Mapping[str, t.Union[Bookmarks,
t.Iterable[str]]] = None,
bookmarks_supplier: _T_BmSupplier = None,
bookmarks_consumer: _T_BmConsumer = None
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
) -> AsyncBookmarkManager:
"""Create a :class:`.AsyncBookmarkManager` with default implementation.
Expand Down
4 changes: 3 additions & 1 deletion neo4j/_async/work/result.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,8 @@
if t.TYPE_CHECKING:
import typing_extensions as te



from ..._async_compat.util import AsyncUtil
from ..._codec.hydration import BrokenHydrationObject
from ..._data import (
Expand Down Expand Up @@ -517,7 +519,7 @@ async def graph(self) -> Graph:
return self._hydration_scope.get_graph()

async def value(
self, key: _T_ResultKey = 0, default: object = None
self, key: _T_ResultKey = 0, default: t.Optional[object] = None
) -> t.List[t.Any]:
"""Helper function that return the remainder of the result as a list of values.
Expand Down
10 changes: 6 additions & 4 deletions neo4j/_async/work/session.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,8 @@
_R = t.TypeVar("_R")
_P = te.ParamSpec("_P")



from ..._async_compat import async_sleep
from ..._async_compat.util import AsyncUtil
from ..._conf import SessionConfig
Expand Down Expand Up @@ -236,7 +238,7 @@ def cancel(self) -> None:
async def run(
self,
query: t.Union[str, Query],
parameters: t.Dict[str, t.Any] = None,
parameters: t.Optional[t.Dict[str, t.Any]] = None,
**kwargs: t.Any
) -> AsyncResult:
"""Run a Cypher query within an auto-commit transaction.
Expand Down Expand Up @@ -321,7 +323,7 @@ async def last_bookmark(self) -> t.Optional[str]:
if self._auto_result:
await self._auto_result.consume()

if self._transaction and self._transaction._closed:
if self._transaction and self._transaction._closed():
await self._update_bookmark(self._transaction._database,
self._transaction._bookmark)
self._transaction = None
Expand Down Expand Up @@ -405,8 +407,8 @@ async def _open_transaction(

async def begin_transaction(
self,
metadata: t.Dict[str, t.Any] = None,
timeout: float = None
metadata: t.Optional[t.Dict[str, t.Any]] = None,
timeout: t.Optional[float] = None
) -> AsyncTransaction:
""" Begin a new unmanaged transaction. Creates a new :class:`.AsyncTransaction` within this session.
At most one transaction may exist in a session at any point in time.
Expand Down
2 changes: 1 addition & 1 deletion neo4j/_async/work/transaction.py
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ async def _consume_results(self):
async def run(
self,
query: str,
parameters: t.Dict[str, t.Any] = None,
parameters: t.Optional[t.Dict[str, t.Any]] = None,
**kwparameters: t.Any
) -> AsyncResult:
""" Run a Cypher query within the context of this transaction.
Expand Down
6 changes: 4 additions & 2 deletions neo4j/_data.py
Original file line number Diff line number Diff line change
Expand Up @@ -140,7 +140,7 @@ def __getslice__(self, start, stop):
values = tuple(self)[key]
return self.__class__(zip(keys, values))

def get(self, key: str, default: object = None) -> t.Any:
def get(self, key: str, default: t.Optional[object] = None) -> t.Any:
""" Obtain a value from the record by key, returning a default
value if the key does not exist.
Expand Down Expand Up @@ -177,7 +177,9 @@ def index(self, key: _T_K) -> int: # type: ignore[override]
else:
raise TypeError(key)

def value(self, key: _T_K = 0, default: object = None) -> t.Any:
def value(
self, key: _T_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
specified item does not exist, the default value is returned.
Expand Down
16 changes: 7 additions & 9 deletions neo4j/_spatial/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,17 +49,15 @@ class Point(t.Tuple[float, ...]):
#: be interpreted in.
srid: t.Optional[int]

@property
def x(self) -> float:
...
if t.TYPE_CHECKING:
@property
def x(self) -> float: ...

@property
def y(self) -> float:
...
@property
def y(self) -> float: ...

@property
def z(self) -> float:
...
@property
def z(self) -> float: ...

def __new__(cls, iterable: t.Iterable[float]) -> Point:
return tuple.__new__(cls, map(float, iterable))
Expand Down
8 changes: 4 additions & 4 deletions neo4j/_sync/bookmark_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,10 +45,10 @@ def _bookmarks_to_set(
class Neo4jBookmarkManager(BookmarkManager):
def __init__(
self,
initial_bookmarks: t.Mapping[str, t.Union[Bookmarks,
t.Iterable[str]]] = None,
bookmarks_supplier: T_BmSupplier = None,
bookmarks_consumer: T_BmConsumer = None
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
) -> None:
super().__init__()
self._bookmarks_supplier = bookmarks_supplier
Expand Down
8 changes: 4 additions & 4 deletions neo4j/_sync/driver.py
Original file line number Diff line number Diff line change
Expand Up @@ -217,10 +217,10 @@ def driver(cls, uri, *, auth=None, **config) -> Driver:
)
def bookmark_manager(
cls,
initial_bookmarks: t.Mapping[str, t.Union[Bookmarks,
t.Iterable[str]]] = None,
bookmarks_supplier: _T_BmSupplier = None,
bookmarks_consumer: _T_BmConsumer = None
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
) -> BookmarkManager:
"""Create a :class:`.BookmarkManager` with default implementation.
Expand Down
4 changes: 3 additions & 1 deletion neo4j/_sync/work/result.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,8 @@
if t.TYPE_CHECKING:
import typing_extensions as te



from ..._async_compat.util import Util
from ..._codec.hydration import BrokenHydrationObject
from ..._data import (
Expand Down Expand Up @@ -517,7 +519,7 @@ def graph(self) -> Graph:
return self._hydration_scope.get_graph()

def value(
self, key: _T_ResultKey = 0, default: object = None
self, key: _T_ResultKey = 0, default: t.Optional[object] = None
) -> t.List[t.Any]:
"""Helper function that return the remainder of the result as a list of values.
Expand Down
10 changes: 6 additions & 4 deletions neo4j/_sync/work/session.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,8 @@
_R = t.TypeVar("_R")
_P = te.ParamSpec("_P")



from ..._async_compat import sleep
from ..._async_compat.util import Util
from ..._conf import SessionConfig
Expand Down Expand Up @@ -236,7 +238,7 @@ def cancel(self) -> None:
def run(
self,
query: t.Union[str, Query],
parameters: t.Dict[str, t.Any] = None,
parameters: t.Optional[t.Dict[str, t.Any]] = None,
**kwargs: t.Any
) -> Result:
"""Run a Cypher query within an auto-commit transaction.
Expand Down Expand Up @@ -321,7 +323,7 @@ def last_bookmark(self) -> t.Optional[str]:
if self._auto_result:
self._auto_result.consume()

if self._transaction and self._transaction._closed:
if self._transaction and self._transaction._closed():
self._update_bookmark(self._transaction._database,
self._transaction._bookmark)
self._transaction = None
Expand Down Expand Up @@ -405,8 +407,8 @@ def _open_transaction(

def begin_transaction(
self,
metadata: t.Dict[str, t.Any] = None,
timeout: float = None
metadata: t.Optional[t.Dict[str, t.Any]] = None,
timeout: t.Optional[float] = None
) -> Transaction:
""" Begin a new unmanaged transaction. Creates a new :class:`.Transaction` within this session.
At most one transaction may exist in a session at any point in time.
Expand Down
2 changes: 1 addition & 1 deletion neo4j/_sync/work/transaction.py
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ def _consume_results(self):
def run(
self,
query: str,
parameters: t.Dict[str, t.Any] = None,
parameters: t.Optional[t.Dict[str, t.Any]] = None,
**kwparameters: t.Any
) -> Result:
""" Run a Cypher query within the context of this transaction.
Expand Down
13 changes: 5 additions & 8 deletions neo4j/addressing.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,10 +44,7 @@ class _WithPeerName(te.Protocol):
def getpeername(self) -> tuple: ...


assert type(tuple) is type


class _AddressMeta(type):
class _AddressMeta(type(tuple)): # type: ignore[misc]

def __init__(cls, *args, **kwargs):
super().__init__(*args, **kwargs)
Expand Down Expand Up @@ -95,8 +92,8 @@ def from_socket(
def parse(
cls: t.Type[_T_Address],
s: str,
default_host: str = None,
default_port: int = None
default_host: t.Optional[str] = None,
default_port: t.Optional[int] = None
) -> _T_Address:
if not isinstance(s, str):
raise TypeError("Address.parse requires a string argument")
Expand Down Expand Up @@ -125,8 +122,8 @@ def parse(
def parse_list(
cls: t.Type[_T_Address],
*s: str,
default_host: str = None,
default_port: int = None
default_host: t.Optional[str] = None,
default_port: t.Optional[int] = None
) -> t.List[_T_Address]:
""" Parse a string containing one or more socket addresses, each
separated by whitespace.
Expand Down
8 changes: 6 additions & 2 deletions neo4j/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,8 @@
import typing_extensions as te
from .addressing import Address



from ._meta import deprecated
from .exceptions import ConfigurationError

Expand Down Expand Up @@ -90,7 +92,7 @@ def __init__(
scheme: t.Optional[str],
principal: t.Optional[str],
credentials: t.Optional[str],
realm: str = None,
realm: t.Optional[str] = None,
**parameters: t.Any
) -> None:
self.scheme = scheme
Expand All @@ -110,7 +112,9 @@ def __init__(
AuthToken = Auth


def basic_auth(user: str, password: str, realm: str = None) -> Auth:
def basic_auth(
user: str, password: str, realm: t.Optional[str] = None
) -> Auth:
"""Generate a basic auth token for a given user and password.
This will set the scheme to "basic" for the auth token.
Expand Down
4 changes: 3 additions & 1 deletion neo4j/debug.py
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,9 @@ def __exit__(self, exc_type, exc_val, exc_tb):
"""Disable logging for all loggers."""
self.stop()

def watch(self, level: int = None, out: t.TextIO = None):
def watch(
self, level: t.Optional[int] = None, out: t.Optional[t.TextIO] = None
) -> None:
"""Enable logging for all loggers.
:param level: Minimum log level to show.
Expand Down
7 changes: 6 additions & 1 deletion neo4j/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,8 @@
_T_Session = t.Union["AsyncSession", "Session"]




from ._meta import deprecated


Expand Down Expand Up @@ -148,7 +150,10 @@ class Neo4jError(Exception):

@classmethod
def hydrate(
cls, message: str = None, code: str = None, **metadata: t.Any
cls,
message: t.Optional[str] = None,
code: t.Optional[str] = None,
**metadata: t.Any
) -> Neo4jError:
message = message or "An unknown error occurred"
code = code or "Neo.DatabaseError.General.UnknownError"
Expand Down
6 changes: 3 additions & 3 deletions neo4j/graph/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -166,7 +166,7 @@ def element_id(self) -> str:
"""
return self._element_id

def get(self, name: str, default: object = None) -> t.Any:
def get(self, name: str, default: t.Optional[object] = None) -> t.Any:
""" Get a property value by name, optionally with a default.
"""
return self._properties.get(name, default)
Expand Down Expand Up @@ -225,8 +225,8 @@ def __init__(
graph: Graph,
element_id: str,
id_: int,
n_labels: t.Iterable[str] = None,
properties: t.Dict[str, t.Any] = None
n_labels: t.Optional[t.Iterable[str]] = None,
properties: t.Optional[t.Dict[str, t.Any]] = None
) -> None:
Entity.__init__(self, graph, element_id, id_, properties)
self._labels = frozenset(n_labels or ())
Expand Down
Loading

0 comments on commit 64112ff

Please sign in to comment.