Python type annotations: Proper way to annotate functions returning library object
Question:
What is the proper way to annotate a type function returns in this code?
from requests import Request, Session
def make_request(method: str, url: str) -> ??? : # Response object will be returned
request = Request(method, url).prepare()
session = Session()
r = session.send(request)
return r
Should be Response
imported for that, or TypeVar
should be used?
Answers:
I think you should import Response
and use it. Creating TypeVar
complicates typing for no good reason:
- If your module had already had
Response
used somewhere (and thus imported), you wouldn’t even think about not using it for the type hint.
- If you introduce another function or whatever to this module later and you need
Response
class there, you’ll be stuck with TypeVar
not matching actual Response
s
- If your module is imported by another module (or even third-party one), a function returning
Response
disguised as a custom TypeVar
would make code more confusing.
Do you want this?
from requests import Request, Session, Response
def make_request(method: str, url: str) -> Response : # Response object will be returned
request = Request(method, url).prepare()
session = Session()
r = session.send(request)
return r
What is the proper way to annotate a type function returns in this code?
from requests import Request, Session
def make_request(method: str, url: str) -> ??? : # Response object will be returned
request = Request(method, url).prepare()
session = Session()
r = session.send(request)
return r
Should be Response
imported for that, or TypeVar
should be used?
I think you should import Response
and use it. Creating TypeVar
complicates typing for no good reason:
- If your module had already had
Response
used somewhere (and thus imported), you wouldn’t even think about not using it for the type hint. - If you introduce another function or whatever to this module later and you need
Response
class there, you’ll be stuck withTypeVar
not matching actualResponse
s - If your module is imported by another module (or even third-party one), a function returning
Response
disguised as a customTypeVar
would make code more confusing.
Do you want this?
from requests import Request, Session, Response
def make_request(method: str, url: str) -> Response : # Response object will be returned
request = Request(method, url).prepare()
session = Session()
r = session.send(request)
return r