55# This module is part of asyncpg and is released under
66# the Apache 2.0 License: http://www.apache.org/licenses/LICENSE-2.0
77
8+ from __future__ import annotations
89
910import functools
11+ from typing import TYPE_CHECKING , Generic , Protocol , TypeVar
12+ from typing_extensions import ParamSpec
1013
1114from . import exceptions
1215
16+ if TYPE_CHECKING :
17+ from . import connection
1318
14- def guarded (meth ):
19+ _ConnectionResourceT = TypeVar (
20+ "_ConnectionResourceT" , bound = "ConnectionResource" , contravariant = True
21+ )
22+ _P = ParamSpec ("_P" )
23+ _R = TypeVar ("_R" , covariant = True )
24+
25+
26+ class _ConnectionResourceMethod (
27+ Protocol ,
28+ Generic [_ConnectionResourceT , _R , _P ],
29+ ):
30+ # This indicates that the Protocol is a function and not a lambda
31+ __name__ : str
32+
33+ # Type signature of a method on an instance of _ConnectionResourceT
34+ def __call__ (
35+ _ , self : _ConnectionResourceT , * args : _P .args , ** kwds : _P .kwargs
36+ ) -> _R :
37+ ...
38+
39+
40+ def guarded (
41+ meth : _ConnectionResourceMethod [_ConnectionResourceT , _R , _P ]
42+ ) -> _ConnectionResourceMethod [_ConnectionResourceT , _R , _P ]:
1543 """A decorator to add a sanity check to ConnectionResource methods."""
1644
1745 @functools .wraps (meth )
18- def _check (self , * args , ** kwargs ):
46+ def _check (
47+ self : _ConnectionResourceT , * args : _P .args , ** kwargs : _P .kwargs
48+ ) -> _R :
1949 self ._check_conn_validity (meth .__name__ )
2050 return meth (self , * args , ** kwargs )
2151
@@ -25,11 +55,11 @@ def _check(self, *args, **kwargs):
2555class ConnectionResource :
2656 __slots__ = ('_connection' , '_con_release_ctr' )
2757
28- def __init__ (self , connection ) :
58+ def __init__ (self , connection : connection . Connection ) -> None :
2959 self ._connection = connection
3060 self ._con_release_ctr = connection ._pool_release_ctr
3161
32- def _check_conn_validity (self , meth_name ) :
62+ def _check_conn_validity (self , meth_name : str ) -> None :
3363 con_release_ctr = self ._connection ._pool_release_ctr
3464 if con_release_ctr != self ._con_release_ctr :
3565 raise exceptions .InterfaceError (
0 commit comments