Skip to content

Commit c50aed0

Browse files
robinrobdarnell
authored andcommitted
mypy: Enable no_implicit_optional
"Implicit-optional" mode is on by default, but that default is intended to change in the indefinite future (python/peps#689, python/typing#275). Go ahead and change to the future explicit use of Optional.
1 parent 87b5a4a commit c50aed0

27 files changed

+363
-280
lines changed

docs/httpserver.rst

+1-1
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55

66
HTTP Server
77
-----------
8-
.. autoclass:: HTTPServer(request_callback: Union[httputil.HTTPServerConnectionDelegate, Callable[[httputil.HTTPServerRequest], None]], no_keep_alive: bool = False, xheaders: bool = False, ssl_options: Union[Dict[str, Any], ssl.SSLContext] = None, protocol: str = None, decompress_request: bool = False, chunk_size: int = None, max_header_size: int = None, idle_connection_timeout: float = None, body_timeout: float = None, max_body_size: int = None, max_buffer_size: int = None, trusted_downstream: List[str] = None)
8+
.. autoclass:: HTTPServer(request_callback: Union[httputil.HTTPServerConnectionDelegate, Callable[[httputil.HTTPServerRequest], None]], no_keep_alive: bool = False, xheaders: bool = False, ssl_options: Union[Dict[str, Any], ssl.SSLContext] = None, protocol: Optional[str] = None, decompress_request: bool = False, chunk_size: Optional[int] = None, max_header_size: Optional[int] = None, idle_connection_timeout: Optional[float] = None, body_timeout: Optional[float] = None, max_body_size: Optional[int] = None, max_buffer_size: Optional[int] = None, trusted_downstream: Optional[List[str]] = None)
99
:members:
1010

1111
The public interface of this class is mostly inherited from

docs/web.rst

+1-1
Original file line numberDiff line numberDiff line change
@@ -161,7 +161,7 @@
161161
Application configuration
162162
-------------------------
163163

164-
.. autoclass:: Application(handlers: List[Union[Rule, Tuple]] = None, default_host: str = None, transforms: List[Type[OutputTransform]] = None, **settings)
164+
.. autoclass:: Application(handlers: Optional[List[Union[Rule, Tuple]]] = None, default_host: Optional[str] = None, transforms: Optional[List[Type[OutputTransform]]] = None, **settings)
165165

166166
.. attribute:: settings
167167

setup.cfg

+1
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ license_file = LICENSE
33

44
[mypy]
55
python_version = 3.5
6+
no_implicit_optional = True
67

78
[mypy-tornado.*,tornado.platform.*]
89
disallow_untyped_defs = True

tornado/auth.py

+32-27
Original file line numberDiff line numberDiff line change
@@ -87,7 +87,7 @@ class OpenIdMixin(object):
8787

8888
def authenticate_redirect(
8989
self,
90-
callback_uri: str = None,
90+
callback_uri: Optional[str] = None,
9191
ax_attrs: List[str] = ["name", "email", "language", "username"],
9292
) -> None:
9393
"""Redirects to the authentication URL for this service.
@@ -114,7 +114,7 @@ def authenticate_redirect(
114114
handler.redirect(endpoint + "?" + urllib.parse.urlencode(args))
115115

116116
async def get_authenticated_user(
117-
self, http_client: httpclient.AsyncHTTPClient = None
117+
self, http_client: Optional[httpclient.AsyncHTTPClient] = None
118118
) -> Dict[str, Any]:
119119
"""Fetches the authenticated user data upon redirect.
120120
@@ -146,7 +146,10 @@ async def get_authenticated_user(
146146
return self._on_authentication_verified(resp)
147147

148148
def _openid_args(
149-
self, callback_uri: str, ax_attrs: Iterable[str] = [], oauth_scope: str = None
149+
self,
150+
callback_uri: str,
151+
ax_attrs: Iterable[str] = [],
152+
oauth_scope: Optional[str] = None,
150153
) -> Dict[str, str]:
151154
handler = cast(RequestHandler, self)
152155
url = urllib.parse.urljoin(handler.request.full_url(), callback_uri)
@@ -286,9 +289,9 @@ class OAuthMixin(object):
286289

287290
async def authorize_redirect(
288291
self,
289-
callback_uri: str = None,
290-
extra_params: Dict[str, Any] = None,
291-
http_client: httpclient.AsyncHTTPClient = None,
292+
callback_uri: Optional[str] = None,
293+
extra_params: Optional[Dict[str, Any]] = None,
294+
http_client: Optional[httpclient.AsyncHTTPClient] = None,
292295
) -> None:
293296
"""Redirects the user to obtain OAuth authorization for this service.
294297
@@ -334,7 +337,7 @@ async def authorize_redirect(
334337
self._on_request_token(url, callback_uri, response)
335338

336339
async def get_authenticated_user(
337-
self, http_client: httpclient.AsyncHTTPClient = None
340+
self, http_client: Optional[httpclient.AsyncHTTPClient] = None
338341
) -> Dict[str, Any]:
339342
"""Gets the OAuth authorized user and access token.
340343
@@ -380,7 +383,9 @@ async def get_authenticated_user(
380383
return user
381384

382385
def _oauth_request_token_url(
383-
self, callback_uri: str = None, extra_params: Dict[str, Any] = None
386+
self,
387+
callback_uri: Optional[str] = None,
388+
extra_params: Optional[Dict[str, Any]] = None,
384389
) -> str:
385390
handler = cast(RequestHandler, self)
386391
consumer_token = self._oauth_consumer_token()
@@ -547,11 +552,11 @@ class OAuth2Mixin(object):
547552

548553
def authorize_redirect(
549554
self,
550-
redirect_uri: str = None,
551-
client_id: str = None,
552-
client_secret: str = None,
553-
extra_params: Dict[str, Any] = None,
554-
scope: str = None,
555+
redirect_uri: Optional[str] = None,
556+
client_id: Optional[str] = None,
557+
client_secret: Optional[str] = None,
558+
extra_params: Optional[Dict[str, Any]] = None,
559+
scope: Optional[str] = None,
555560
response_type: str = "code",
556561
) -> None:
557562
"""Redirects the user to obtain OAuth authorization for this service.
@@ -582,11 +587,11 @@ def authorize_redirect(
582587

583588
def _oauth_request_token_url(
584589
self,
585-
redirect_uri: str = None,
586-
client_id: str = None,
587-
client_secret: str = None,
588-
code: str = None,
589-
extra_params: Dict[str, Any] = None,
590+
redirect_uri: Optional[str] = None,
591+
client_id: Optional[str] = None,
592+
client_secret: Optional[str] = None,
593+
code: Optional[str] = None,
594+
extra_params: Optional[Dict[str, Any]] = None,
590595
) -> str:
591596
url = self._OAUTH_ACCESS_TOKEN_URL # type: ignore
592597
args = {} # type: Dict[str, str]
@@ -605,8 +610,8 @@ def _oauth_request_token_url(
605610
async def oauth2_request(
606611
self,
607612
url: str,
608-
access_token: str = None,
609-
post_args: Dict[str, Any] = None,
613+
access_token: Optional[str] = None,
614+
post_args: Optional[Dict[str, Any]] = None,
610615
**args: Any
611616
) -> Any:
612617
"""Fetches the given URL auth an OAuth2 access token.
@@ -709,7 +714,7 @@ async def get(self):
709714
_OAUTH_NO_CALLBACKS = False
710715
_TWITTER_BASE_URL = "https://api.twitter.com/1.1"
711716

712-
async def authenticate_redirect(self, callback_uri: str = None) -> None:
717+
async def authenticate_redirect(self, callback_uri: Optional[str] = None) -> None:
713718
"""Just like `~OAuthMixin.authorize_redirect`, but
714719
auto-redirects if authorized.
715720
@@ -735,7 +740,7 @@ async def twitter_request(
735740
self,
736741
path: str,
737742
access_token: Dict[str, Any],
738-
post_args: Dict[str, Any] = None,
743+
post_args: Optional[Dict[str, Any]] = None,
739744
**args: Any
740745
) -> Any:
741746
"""Fetches the given API path, e.g., ``statuses/user_timeline/btaylor``
@@ -930,7 +935,7 @@ async def get_authenticated_user(
930935
client_id: str,
931936
client_secret: str,
932937
code: str,
933-
extra_fields: Dict[str, Any] = None,
938+
extra_fields: Optional[Dict[str, Any]] = None,
934939
) -> Optional[Dict[str, Any]]:
935940
"""Handles the login for the Facebook user, returning a user object.
936941
@@ -1034,8 +1039,8 @@ async def get(self):
10341039
async def facebook_request(
10351040
self,
10361041
path: str,
1037-
access_token: str = None,
1038-
post_args: Dict[str, Any] = None,
1042+
access_token: Optional[str] = None,
1043+
post_args: Optional[Dict[str, Any]] = None,
10391044
**args: Any
10401045
) -> Any:
10411046
"""Fetches the given relative API path, e.g., "/btaylor/picture"
@@ -1099,7 +1104,7 @@ def _oauth_signature(
10991104
method: str,
11001105
url: str,
11011106
parameters: Dict[str, Any] = {},
1102-
token: Dict[str, Any] = None,
1107+
token: Optional[Dict[str, Any]] = None,
11031108
) -> bytes:
11041109
"""Calculates the HMAC-SHA1 OAuth signature for the given request.
11051110
@@ -1132,7 +1137,7 @@ def _oauth10a_signature(
11321137
method: str,
11331138
url: str,
11341139
parameters: Dict[str, Any] = {},
1135-
token: Dict[str, Any] = None,
1140+
token: Optional[Dict[str, Any]] = None,
11361141
) -> bytes:
11371142
"""Calculates the HMAC-SHA1 OAuth 1.0a signature for the given request.
11381143

tornado/curl_httpclient.py

+7-4
Original file line numberDiff line numberDiff line change
@@ -36,18 +36,18 @@
3636
)
3737
from tornado.log import app_log
3838

39-
from typing import Dict, Any, Callable, Union
39+
from typing import Dict, Any, Callable, Union, Tuple, Optional
4040
import typing
4141

4242
if typing.TYPE_CHECKING:
43-
from typing import Deque, Tuple, Optional # noqa: F401
43+
from typing import Deque # noqa: F401
4444

4545
curl_log = logging.getLogger("tornado.curl_httpclient")
4646

4747

4848
class CurlAsyncHTTPClient(AsyncHTTPClient):
4949
def initialize( # type: ignore
50-
self, max_clients: int = 10, defaults: Dict[str, Any] = None
50+
self, max_clients: int = 10, defaults: Optional[Dict[str, Any]] = None
5151
) -> None:
5252
super(CurlAsyncHTTPClient, self).initialize(defaults=defaults)
5353
# Typeshed is incomplete for CurlMulti, so just use Any for now.
@@ -255,7 +255,10 @@ def _process_queue(self) -> None:
255255
break
256256

257257
def _finish(
258-
self, curl: pycurl.Curl, curl_error: int = None, curl_message: str = None
258+
self,
259+
curl: pycurl.Curl,
260+
curl_error: Optional[int] = None,
261+
curl_message: Optional[str] = None,
259262
) -> None:
260263
info = curl.info # type: ignore
261264
curl.info = None # type: ignore

tornado/http1connection.py

+10-10
Original file line numberDiff line numberDiff line change
@@ -75,11 +75,11 @@ class HTTP1ConnectionParameters(object):
7575
def __init__(
7676
self,
7777
no_keep_alive: bool = False,
78-
chunk_size: int = None,
79-
max_header_size: int = None,
80-
header_timeout: float = None,
81-
max_body_size: int = None,
82-
body_timeout: float = None,
78+
chunk_size: Optional[int] = None,
79+
max_header_size: Optional[int] = None,
80+
header_timeout: Optional[float] = None,
81+
max_body_size: Optional[int] = None,
82+
body_timeout: Optional[float] = None,
8383
decompress: bool = False,
8484
) -> None:
8585
"""
@@ -113,8 +113,8 @@ def __init__(
113113
self,
114114
stream: iostream.IOStream,
115115
is_client: bool,
116-
params: HTTP1ConnectionParameters = None,
117-
context: object = None,
116+
params: Optional[HTTP1ConnectionParameters] = None,
117+
context: Optional[object] = None,
118118
) -> None:
119119
"""
120120
:arg stream: an `.IOStream`
@@ -377,7 +377,7 @@ def write_headers(
377377
self,
378378
start_line: Union[httputil.RequestStartLine, httputil.ResponseStartLine],
379379
headers: httputil.HTTPHeaders,
380-
chunk: bytes = None,
380+
chunk: Optional[bytes] = None,
381381
) -> "Future[None]":
382382
"""Implements `.HTTPConnection.write_headers`."""
383383
lines = []
@@ -765,8 +765,8 @@ class HTTP1ServerConnection(object):
765765
def __init__(
766766
self,
767767
stream: iostream.IOStream,
768-
params: HTTP1ConnectionParameters = None,
769-
context: object = None,
768+
params: Optional[HTTP1ConnectionParameters] = None,
769+
context: Optional[object] = None,
770770
) -> None:
771771
"""
772772
:arg stream: an `.IOStream`

tornado/httpclient.py

+48-41
Original file line numberDiff line numberDiff line change
@@ -87,7 +87,9 @@ class HTTPClient(object):
8787
"""
8888

8989
def __init__(
90-
self, async_client_class: Type["AsyncHTTPClient"] = None, **kwargs: Any
90+
self,
91+
async_client_class: "Optional[Type[AsyncHTTPClient]]" = None,
92+
**kwargs: Any
9193
) -> None:
9294
# Initialize self._closed at the beginning of the constructor
9395
# so that an exception raised here doesn't lead to confusing
@@ -211,7 +213,7 @@ def __new__(cls, force_instance: bool = False, **kwargs: Any) -> "AsyncHTTPClien
211213
instance_cache[instance.io_loop] = instance
212214
return instance
213215

214-
def initialize(self, defaults: Dict[str, Any] = None) -> None:
216+
def initialize(self, defaults: Optional[Dict[str, Any]] = None) -> None:
215217
self.io_loop = IOLoop.current()
216218
self.defaults = dict(HTTPRequest._DEFAULTS)
217219
if defaults is not None:
@@ -357,37 +359,39 @@ def __init__(
357359
self,
358360
url: str,
359361
method: str = "GET",
360-
headers: Union[Dict[str, str], httputil.HTTPHeaders] = None,
361-
body: Union[bytes, str] = None,
362-
auth_username: str = None,
363-
auth_password: str = None,
364-
auth_mode: str = None,
365-
connect_timeout: float = None,
366-
request_timeout: float = None,
367-
if_modified_since: Union[float, datetime.datetime] = None,
368-
follow_redirects: bool = None,
369-
max_redirects: int = None,
370-
user_agent: str = None,
371-
use_gzip: bool = None,
372-
network_interface: str = None,
373-
streaming_callback: Callable[[bytes], None] = None,
374-
header_callback: Callable[[str], None] = None,
375-
prepare_curl_callback: Callable[[Any], None] = None,
376-
proxy_host: str = None,
377-
proxy_port: int = None,
378-
proxy_username: str = None,
379-
proxy_password: str = None,
380-
proxy_auth_mode: str = None,
381-
allow_nonstandard_methods: bool = None,
382-
validate_cert: bool = None,
383-
ca_certs: str = None,
384-
allow_ipv6: bool = None,
385-
client_key: str = None,
386-
client_cert: str = None,
387-
body_producer: Callable[[Callable[[bytes], None]], "Future[None]"] = None,
362+
headers: Optional[Union[Dict[str, str], httputil.HTTPHeaders]] = None,
363+
body: Optional[Union[bytes, str]] = None,
364+
auth_username: Optional[str] = None,
365+
auth_password: Optional[str] = None,
366+
auth_mode: Optional[str] = None,
367+
connect_timeout: Optional[float] = None,
368+
request_timeout: Optional[float] = None,
369+
if_modified_since: Optional[Union[float, datetime.datetime]] = None,
370+
follow_redirects: Optional[bool] = None,
371+
max_redirects: Optional[int] = None,
372+
user_agent: Optional[str] = None,
373+
use_gzip: Optional[bool] = None,
374+
network_interface: Optional[str] = None,
375+
streaming_callback: Optional[Callable[[bytes], None]] = None,
376+
header_callback: Optional[Callable[[str], None]] = None,
377+
prepare_curl_callback: Optional[Callable[[Any], None]] = None,
378+
proxy_host: Optional[str] = None,
379+
proxy_port: Optional[int] = None,
380+
proxy_username: Optional[str] = None,
381+
proxy_password: Optional[str] = None,
382+
proxy_auth_mode: Optional[str] = None,
383+
allow_nonstandard_methods: Optional[bool] = None,
384+
validate_cert: Optional[bool] = None,
385+
ca_certs: Optional[str] = None,
386+
allow_ipv6: Optional[bool] = None,
387+
client_key: Optional[str] = None,
388+
client_cert: Optional[str] = None,
389+
body_producer: Optional[
390+
Callable[[Callable[[bytes], None]], "Future[None]"]
391+
] = None,
388392
expect_100_continue: bool = False,
389-
decompress_response: bool = None,
390-
ssl_options: Union[Dict[str, Any], ssl.SSLContext] = None,
393+
decompress_response: Optional[bool] = None,
394+
ssl_options: Optional[Union[Dict[str, Any], ssl.SSLContext]] = None,
391395
) -> None:
392396
r"""All parameters except ``url`` are optional.
393397
@@ -624,14 +628,14 @@ def __init__(
624628
self,
625629
request: HTTPRequest,
626630
code: int,
627-
headers: httputil.HTTPHeaders = None,
628-
buffer: BytesIO = None,
629-
effective_url: str = None,
630-
error: BaseException = None,
631-
request_time: float = None,
632-
time_info: Dict[str, float] = None,
633-
reason: str = None,
634-
start_time: float = None,
631+
headers: Optional[httputil.HTTPHeaders] = None,
632+
buffer: Optional[BytesIO] = None,
633+
effective_url: Optional[str] = None,
634+
error: Optional[BaseException] = None,
635+
request_time: Optional[float] = None,
636+
time_info: Optional[Dict[str, float]] = None,
637+
reason: Optional[str] = None,
638+
start_time: Optional[float] = None,
635639
) -> None:
636640
if isinstance(request, _RequestProxy):
637641
self.request = request.request
@@ -703,7 +707,10 @@ class HTTPClientError(Exception):
703707
"""
704708

705709
def __init__(
706-
self, code: int, message: str = None, response: HTTPResponse = None
710+
self,
711+
code: int,
712+
message: Optional[str] = None,
713+
response: Optional[HTTPResponse] = None,
707714
) -> None:
708715
self.code = code
709716
self.message = message or httputil.responses.get(code, "Unknown")

0 commit comments

Comments
 (0)