Skip to content

Commit 1c4241d

Browse files
committed
Use specific ignore comments and updates for mypy 0.780
1 parent b468732 commit 1c4241d

File tree

9 files changed

+55
-48
lines changed

9 files changed

+55
-48
lines changed

.gitignore

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,6 @@ docs/_build
3434
/.eggs
3535
/.vscode
3636
/.mypy_cache
37-
/.venv
37+
/.venv*
3838
/.ci
3939
/.vim

asyncpg/cluster.py

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -126,15 +126,15 @@ def get_status(self) -> str:
126126
return self._test_connection(timeout=0)
127127
else:
128128
raise ClusterError(
129-
'pg_ctl status exited with status {:d}: {}'.format(
129+
'pg_ctl status exited with status {:d}: {}'.format( # type: ignore[str-bytes-safe] # noqa: E501
130130
process.returncode, stderr))
131131

132132
async def connect(self,
133133
loop: typing.Optional[asyncio.AbstractEventLoop] = None,
134134
**kwargs: typing.Any) -> 'connection.Connection':
135135
conn_info = self.get_connection_spec() # type: typing.Optional[typing.Any] # noqa: E501
136-
conn_info.update(kwargs)
137-
return await asyncpg.connect(loop=loop, **conn_info)
136+
conn_info.update(kwargs) # type: ignore[union-attr]
137+
return await asyncpg.connect(loop=loop, **conn_info) # type: ignore[misc] # noqa: E501
138138

139139
def init(self, **settings: str) -> str:
140140
"""Initialize cluster."""
@@ -301,7 +301,7 @@ def _get_connection_spec(self) -> typing.Optional[_ConnectionSpec]:
301301
if self._connection_addr is not None:
302302
if self._connection_spec_override:
303303
args = self._connection_addr.copy()
304-
args.update(self._connection_spec_override) # type: ignore
304+
args.update(self._connection_spec_override) # type: ignore[arg-type] # noqa: E501
305305
return args
306306
else:
307307
return self._connection_addr
@@ -401,7 +401,7 @@ def add_hba_entry(self, *, type: str = 'host',
401401

402402
if auth_options is not None:
403403
record += ' ' + ' '.join(
404-
'{}={}'.format(k, v) for k, v in auth_options)
404+
'{}={}'.format(k, v) for k, v in auth_options.items())
405405

406406
try:
407407
with open(pg_hba, 'a') as f:
@@ -516,7 +516,7 @@ def _test_connection(self, timeout: int = 60) -> str:
516516

517517
try:
518518
con = loop.run_until_complete(
519-
asyncpg.connect(database='postgres',
519+
asyncpg.connect(database='postgres', # type: ignore[misc] # noqa: E501
520520
user='postgres',
521521
timeout=5, loop=loop,
522522
**self._connection_addr))
@@ -544,7 +544,7 @@ def _run_pg_config(self, pg_config_path: str) -> typing.Dict[str, str]:
544544
stdout, stderr = process.stdout, process.stderr
545545

546546
if process.returncode != 0:
547-
raise ClusterError('pg_config exited with status {:d}: {}'.format(
547+
raise ClusterError('pg_config exited with status {:d}: {}'.format( # type: ignore[str-bytes-safe] # noqa: E501
548548
process.returncode, stderr))
549549
else:
550550
config = {}
@@ -601,7 +601,7 @@ def _get_pg_version(self) -> 'types.ServerVersion':
601601

602602
if process.returncode != 0:
603603
raise ClusterError(
604-
'postgres --version exited with status {:d}: {}'.format(
604+
'postgres --version exited with status {:d}: {}'.format( # type: ignore[str-bytes-safe] # noqa: E501
605605
process.returncode, stderr))
606606

607607
version_string = stdout.decode('utf-8').strip(' \n')

asyncpg/compat.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@ async def wrapper(self: typing.Any) -> typing.Any:
3535
return func(self)
3636
return typing.cast(_F_35, wrapper)
3737
else:
38-
def aiter_compat(func: _F) -> _F: # type: ignore
38+
def aiter_compat(func: _F) -> _F: # type: ignore[misc]
3939
return func
4040

4141

@@ -89,7 +89,7 @@ def get_pg_home_directory() -> typing.Optional[pathlib.Path]:
8989
# home directory, whereas Postgres stores its config in
9090
# %AppData% on Windows.
9191
buf = ctypes.create_unicode_buffer(ctypes.wintypes.MAX_PATH)
92-
r = ctypes.windll.shell32.SHGetFolderPathW(0, CSIDL_APPDATA, 0, 0, buf) # type: ignore # noqa: E501
92+
r = ctypes.windll.shell32.SHGetFolderPathW(0, CSIDL_APPDATA, 0, 0, buf) # type: ignore[attr-defined] # noqa: E501
9393
if r:
9494
return None
9595
else:

asyncpg/connect_utils.py

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -317,7 +317,7 @@ def _parse_connect_dsn_and_args(*, dsn: typing.Optional[str],
317317
if 'sslmode' in query_str:
318318
val_str = query_str.pop('sslmode')
319319
if ssl is None:
320-
ssl = val_str
320+
ssl = val_str # type: ignore[assignment]
321321

322322
if query_str:
323323
if server_settings is None:
@@ -392,17 +392,17 @@ def _parse_connect_dsn_and_args(*, dsn: typing.Optional[str],
392392
if passfile is None:
393393
homedir = compat.get_pg_home_directory()
394394
if homedir:
395-
passfile = homedir / PGPASSFILE
395+
passfile = homedir / PGPASSFILE # type: ignore[assignment]
396396
else:
397397
passfile = None
398398
else:
399-
passfile = pathlib.Path(passfile)
399+
passfile = pathlib.Path(passfile) # type: ignore[assignment]
400400

401401
if passfile is not None:
402402
password = _read_password_from_pgpass(
403403
hosts=auth_hosts, ports=port,
404404
database=database, user=user,
405-
passfile=passfile)
405+
passfile=passfile) # type: ignore[arg-type]
406406

407407
addrs = [] # type: typing.List[AddrType]
408408
for h, p in zip(host, port):
@@ -420,7 +420,7 @@ def _parse_connect_dsn_and_args(*, dsn: typing.Optional[str],
420420
'could not determine the database address to connect to')
421421

422422
if ssl is None:
423-
ssl = os.getenv('PGSSLMODE')
423+
ssl = os.getenv('PGSSLMODE') # type: ignore[assignment]
424424

425425
# ssl_is_advisory is only allowed to come from the sslmode parameter.
426426
ssl_is_advisory = None
@@ -594,7 +594,7 @@ async def _create_ssl_connection(protocol_factory: typing.Callable[[],
594594
typing.Tuple[asyncio.WriteTransport, TLSUpgradeProto],
595595
await loop.create_connection(
596596
lambda: TLSUpgradeProto(loop, host, port,
597-
typing.cast(ssl_module.SSLContext,
597+
typing.cast(typing.Any,
598598
ssl_context),
599599
ssl_is_advisory),
600600
host, port))
@@ -614,7 +614,7 @@ async def _create_ssl_connection(protocol_factory: typing.Callable[[],
614614
asyncio.WriteTransport,
615615
await typing.cast(typing.Any, loop).start_tls(
616616
tr, pr,
617-
typing.cast(ssl_module.SSLContext, ssl_context),
617+
typing.cast(typing.Any, ssl_context),
618618
server_hostname=host))
619619
except (Exception, asyncio.CancelledError):
620620
tr.close()
@@ -709,7 +709,7 @@ async def _connect_addr(
709709
tr.close()
710710
raise
711711

712-
con = connection_class(pr, tr, loop, addr, config, # type: ignore
712+
con = connection_class(pr, tr, loop, addr, config, # type: ignore[call-arg] # noqa: E501
713713
params_input)
714714
pr.set_connection(con)
715715
return con
@@ -812,7 +812,7 @@ def _set_nodelay(sock: typing.Any) -> None:
812812
def _create_future(loop: typing.Optional[asyncio.AbstractEventLoop]) \
813813
-> 'asyncio.Future[typing.Any]':
814814
try:
815-
create_future = loop.create_future # type: ignore
815+
create_future = loop.create_future # type: ignore[union-attr]
816816
except AttributeError:
817817
return asyncio.Future(loop=loop)
818818
else:

asyncpg/connection.py

Lines changed: 14 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,7 @@
3838
_Connection = typing.TypeVar('_Connection', bound='Connection')
3939
_Writer = typing.Callable[[bytes],
4040
typing.Coroutine[typing.Any, typing.Any, None]]
41+
_Record = typing.TypeVar('_Record', bound='_cprotocol.Record')
4142
_RecordsType = typing.List['_cprotocol.Record']
4243
_RecordsExtraType = typing.Tuple[_RecordsType, bytes, bool]
4344
_AnyCallable = typing.Callable[..., typing.Any]
@@ -548,7 +549,7 @@ def cursor(
548549
prefetch: typing.Optional[int] = None,
549550
timeout: typing.Optional[float] = None,
550551
record_class: typing.Optional[typing.Any] = None
551-
) -> cursor.CursorFactory:
552+
) -> 'cursor.CursorFactory[_cprotocol.Record]':
552553
"""Return a *cursor factory* for the specified query.
553554
554555
:param args:
@@ -586,7 +587,7 @@ async def prepare(
586587
*,
587588
timeout: typing.Optional[float] = None,
588589
record_class: typing.Optional[typing.Any] = None
589-
) -> prepared_stmt.PreparedStatement:
590+
) -> prepared_stmt.PreparedStatement['_cprotocol.Record']:
590591
"""Create a *prepared statement* for the specified query.
591592
592593
:param str query:
@@ -619,7 +620,7 @@ async def _prepare(
619620
timeout: typing.Optional[float] = None,
620621
use_cache: bool = False,
621622
record_class: typing.Optional[typing.Any] = None
622-
) -> prepared_stmt.PreparedStatement:
623+
) -> prepared_stmt.PreparedStatement['_cprotocol.Record']:
623624
self._check_open()
624625
stmt = await self._get_statement(
625626
query,
@@ -1078,7 +1079,7 @@ async def _copy_out(self, copy_stmt: str,
10781079
output: OutputType[typing.AnyStr],
10791080
timeout: typing.Optional[float]) -> str:
10801081
try:
1081-
path = compat.fspath(output) # type: typing.Optional[typing.AnyStr] # type: ignore # noqa: E501
1082+
path = compat.fspath(output) # type: typing.Optional[typing.AnyStr] # type: ignore[arg-type] # noqa: E501
10821083
except TypeError:
10831084
# output is not a path-like object
10841085
path = None
@@ -1105,7 +1106,7 @@ async def _copy_out(self, copy_stmt: str,
11051106
)
11061107

11071108
if writer is None:
1108-
async def _writer(data: bytes) -> None: # type: ignore
1109+
async def _writer(data: bytes) -> None: # type: ignore[return]
11091110
await run_in_executor(None, f.write, data)
11101111

11111112
writer = _writer
@@ -1120,7 +1121,7 @@ async def _copy_in(self, copy_stmt: str,
11201121
source: SourceType[typing.AnyStr],
11211122
timeout: typing.Optional[float]) -> str:
11221123
try:
1123-
path = compat.fspath(source) # type: typing.Optional[typing.AnyStr] # type: ignore # noqa: E501
1124+
path = compat.fspath(source) # type: typing.Optional[typing.AnyStr] # type: ignore[arg-type] # noqa: E501
11241125
except TypeError:
11251126
# source is not a path-like object
11261127
path = None
@@ -1159,7 +1160,7 @@ async def __anext__(self) -> bytes:
11591160
if len(data) == 0:
11601161
raise StopAsyncIteration
11611162
else:
1162-
return data # type: ignore
1163+
return data # type: ignore[return-value]
11631164

11641165
reader = _Reader()
11651166

@@ -1434,7 +1435,7 @@ def _abort(self) -> None:
14341435
# Put the connection into the aborted state.
14351436
self._aborted = True
14361437
self._protocol.abort()
1437-
self._protocol = None # type: ignore
1438+
self._protocol = None # type: ignore[assignment]
14381439

14391440
def _cleanup(self) -> None:
14401441
self._call_termination_listeners()
@@ -1533,7 +1534,7 @@ async def _cancel(self, waiter: 'asyncio.Future[None]') -> None:
15331534
waiter.set_exception(ex)
15341535
finally:
15351536
self._cancellations.discard(
1536-
compat.current_asyncio_task(self._loop))
1537+
compat.current_asyncio_task(self._loop)) # type: ignore[arg-type] # noqa: E501
15371538
if not waiter.done():
15381539
waiter.set_result(None)
15391540

@@ -2032,7 +2033,7 @@ async def connect(dsn: typing.Optional[str] = None, *,
20322033
max_cacheable_statement_size: int = 1024 * 15,
20332034
command_timeout: typing.Optional[float] = None,
20342035
ssl: typing.Optional[connect_utils.SSLType] = None,
2035-
connection_class: typing.Type[_Connection] = Connection, # type: ignore # noqa: E501
2036+
connection_class: typing.Type[_Connection] = Connection, # type: ignore[assignment] # noqa: E501
20362037
record_class: typing.Optional[typing.Any] = protocol.Record,
20372038
server_settings: typing.Optional[
20382039
typing.Dict[str, str]] = None) -> _Connection:
@@ -2488,15 +2489,15 @@ def _extract_stack(limit: int = 10) -> str:
24882489
frame = sys._getframe().f_back
24892490
try:
24902491
stack = traceback.StackSummary.extract(
2491-
traceback.walk_stack(frame), lookup_lines=False) # type: typing.Union[traceback.StackSummary, typing.List[traceback.FrameSummary]] # noqa: E501
2492+
traceback.walk_stack(frame), lookup_lines=False) # type: ignore[arg-type] # noqa: E501
24922493
finally:
24932494
del frame
24942495

2495-
apg_path = asyncpg.__path__[0]
2496+
apg_path = asyncpg.__path__[0] # type: ignore[attr-defined]
24962497
i = 0
24972498
while i < len(stack) and stack[i][0].startswith(apg_path):
24982499
i += 1
2499-
stack = stack[i:i + limit]
2500+
stack = stack[i:i + limit] # type: ignore[assignment]
25002501

25012502
stack.reverse()
25022503
return ''.join(traceback.format_list(stack))

asyncpg/cursor.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@
2424
_Record = typing.TypeVar('_Record', bound='_cprotocol.Record')
2525

2626

27-
class CursorFactory(connresource.ConnectionResource):
27+
class CursorFactory(connresource.ConnectionResource, typing.Generic[_Record]):
2828
"""A cursor interface for the results of a query.
2929
3030
A cursor interface can be used to initiate efficient traversal of the
@@ -62,7 +62,7 @@ def __init__(
6262

6363
@compat.aiter_compat
6464
@connresource.guarded
65-
def __aiter__(self) -> 'CursorIterator[_cprotocol.Record]':
65+
def __aiter__(self) -> 'CursorIterator[_Record]':
6666
prefetch = 50 if self._prefetch is None else self._prefetch
6767
return CursorIterator(
6868
self._connection,
@@ -76,7 +76,7 @@ def __aiter__(self) -> 'CursorIterator[_cprotocol.Record]':
7676

7777
@connresource.guarded
7878
def __await__(self) -> typing.Generator[
79-
typing.Any, None, 'Cursor[_cprotocol.Record]']:
79+
typing.Any, None, 'Cursor[_Record]']:
8080
if self._prefetch is not None:
8181
raise exceptions.InterfaceError(
8282
'prefetch argument can only be specified for iterable cursor')
@@ -86,7 +86,7 @@ def __await__(self) -> typing.Generator[
8686
self._state,
8787
self._args,
8888
self._record_class
89-
) # type: Cursor[_cprotocol.Record]
89+
) # type: Cursor[_Record]
9090
return cursor._init(self._timeout).__await__()
9191

9292
def __del__(self) -> None:
@@ -201,7 +201,7 @@ def __repr__(self) -> str:
201201

202202
return '<{}.{} "{!s:.30}" {}{:#x}>'.format(
203203
mod, self.__class__.__name__,
204-
self._state.query,
204+
self._state.query, # type: ignore[union-attr]
205205
' '.join(attrs), id(self))
206206

207207
def __del__(self) -> None:

asyncpg/pool.pyi

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -43,10 +43,11 @@ class PoolConnectionProxy(connection._ConnectionProxy,
4343
*, timeout: typing.Optional[float] = ...) -> None: ...
4444
def cursor(self, query: str, *args: typing.Any,
4545
prefetch: typing.Optional[int] = ...,
46-
timeout: typing.Optional[float] = ...) -> cursor.CursorFactory: ...
46+
timeout: typing.Optional[float] = ...) \
47+
-> cursor.CursorFactory[_cprotocol.Record]: ...
4748
async def prepare(self, query: str, *,
4849
timeout: typing.Optional[float] = ...) \
49-
-> prepared_stmt.PreparedStatement: ...
50+
-> prepared_stmt.PreparedStatement[_cprotocol.Record]: ...
5051
async def fetch(self, query: str, *args: typing.Any,
5152
timeout: typing.Optional[float] = ...) \
5253
-> typing.List[_cprotocol.Record]: ...

asyncpg/prepared_stmt.py

Lines changed: 11 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,11 @@
1919
from . import connection as _connection
2020

2121

22-
class PreparedStatement(connresource.ConnectionResource):
22+
_Record = typing.TypeVar('_Record', bound='_cprotocol.Record')
23+
24+
25+
class PreparedStatement(connresource.ConnectionResource,
26+
typing.Generic[_Record]):
2327
"""A representation of a prepared statement."""
2428

2529
__slots__ = ('_state', '_query', '_last_status')
@@ -101,7 +105,8 @@ def get_attributes(self) -> typing.Tuple[types.Attribute, ...]:
101105

102106
@connresource.guarded
103107
def cursor(self, *args: typing.Any, prefetch: typing.Optional[int] = None,
104-
timeout: typing.Optional[float] = None) -> cursor.CursorFactory:
108+
timeout: typing.Optional[float] = None) \
109+
-> cursor.CursorFactory[_Record]:
105110
"""Return a *cursor factory* for the prepared statement.
106111
107112
:param args: Query arguments.
@@ -167,7 +172,7 @@ async def explain(self, *args: typing.Any,
167172
@connresource.guarded
168173
async def fetch(self, *args: typing.Any,
169174
timeout: typing.Optional[float] = None) \
170-
-> typing.List['_cprotocol.Record']:
175+
-> typing.List[_Record]:
171176
r"""Execute the statement and return a list of :class:`Record` objects.
172177
173178
:param str query: Query text
@@ -202,7 +207,7 @@ async def fetchval(self, *args: typing.Any, column: int = 0,
202207
@connresource.guarded
203208
async def fetchrow(self, *args: typing.Any,
204209
timeout: typing.Optional[float] = None) \
205-
-> typing.Optional['_cprotocol.Record']:
210+
-> typing.Optional[_Record]:
206211
"""Execute the statement and return the first row.
207212
208213
:param str query: Query text
@@ -219,7 +224,7 @@ async def fetchrow(self, *args: typing.Any,
219224
async def __bind_execute(self, args: typing.Tuple[typing.Any, ...],
220225
limit: int,
221226
timeout: typing.Optional[float]) \
222-
-> typing.List['_cprotocol.Record']:
227+
-> typing.List[_Record]:
223228
protocol = self._connection._protocol
224229
try:
225230
data, status, _ = await protocol.bind_execute(
@@ -233,7 +238,7 @@ async def __bind_execute(self, args: typing.Tuple[typing.Any, ...],
233238
self._state.mark_closed()
234239
raise
235240
self._last_status = status
236-
return data
241+
return data # type: ignore[return-value]
237242

238243
def _check_open(self, meth_name: str) -> None:
239244
if self._state.closed:

0 commit comments

Comments
 (0)