I am making my first attempt to use type hinting in a new project, and
I'm quickly hitting areas that I'm having trouble understanding.ÿ One of
them is how to write type hints for a method decorator.
Here is an example that illustrates my confusion.ÿ (Sorry for the
length.)
import collections.abc
class BufferScanner(object):
ÿÿÿ @staticmethod....
ÿÿÿ def _check_eof(method: collections.abc.Callable -> (
ÿÿÿÿÿÿÿ collections.abc.Callable
ÿÿÿ ):
I cannot figure out how to correctly specify the Callable argument and
return type for _check_eof().ÿ As indicated by the name, method should
be a method (of the BufferScanner class), so its first positional
argument should always be an instance of BufferScanner, but it could
have any combination of positional and/or keyword arguments after that.
I cannot figure out how to correctly specify the Callable argument and
return type for _check_eof().
them is how to write type hints for a method decorator.
On 18/01/25 12:33, Ian Pilcher via Python-list wrote:
I am making my first attempt to use type hinting in a new project, and...
I'm quickly hitting areas that I'm having trouble understanding.ÿ One of
them is how to write type hints for a method decorator.
Here is an example that illustrates my confusion.ÿ (Sorry for the
length.)
import collections.abc
class BufferScanner(object):
ÿÿÿÿ @staticmethod...
ÿÿÿÿ def _check_eof(method: collections.abc.Callable -> (
ÿÿÿÿÿÿÿÿ collections.abc.Callable
ÿÿÿÿ ):
I cannot figure out how to correctly specify the Callable argument and
return type for _check_eof().ÿ As indicated by the name, method should
be a method (of the BufferScanner class), so its first positional
argument should always be an instance of BufferScanner, but it could
have any combination of positional and/or keyword arguments after that.
Is it a typing problem?
The def is not syntactically-correct (parentheses).
What happens once corrected?
Also, which tool is 'complaining', and what does it have to say?
General comment: as far as type-hints go, rather than trying to learn
how to deal with complex situations, it might be better to ease-in
gradually - add the easy stuff now, and come back to deal with the rest later (otherwise the typing 'tail' is wagging the coding 'dog'!)
T = TypeVar('T')
T = TypeVar('T')
P = ParamSpec('P')
@staticmethod
def _check_eof(method: Callable[Concatenate['BufferScanner', P], T]) -> Callable[Concatenate['BufferScanner', P], bool]:
def wrapper(self: 'BufferScanner', *args: P.args, **kwargs: P.kwargs) -> bool:
Sysop: | Tetrazocine |
---|---|
Location: | Melbourne, VIC, Australia |
Users: | 9 |
Nodes: | 8 (0 / 8) |
Uptime: | 120:03:29 |
Calls: | 161 |
Files: | 21,502 |
Messages: | 78,883 |