Skip to content

Commit aed7305

Browse files
jacopofarjpadilla
authored andcommitted
RFC: Add type hints (jpadilla#344)
* Add mypy to Travis and a simple type hint to _get_default_options * Make flake8 accept unused import required by mypy * Add typing to encode and decode, create encode_bytes in JWS to differentiate from encode in JWT * Use Union type to describe both types of payload
1 parent ee2ab9f commit aed7305

File tree

4 files changed

+44
-11
lines changed

4 files changed

+44
-11
lines changed

.travis.yml

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,9 @@ env:
2525
install:
2626
- pip install -U pip
2727
- pip install -U tox coveralls
28+
- pip install -U mypy
2829
script:
2930
- tox
31+
- mypy --ignore-missing-imports jwt
3032
after_success:
3133
- coveralls

jwt/api_jws.py

Lines changed: 19 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,11 @@
22
import json
33
import warnings
44
from collections import Mapping
5+
try:
6+
# import required by mypy to perform type checking, not used for normal execution
7+
from typing import Callable, Dict, List, Optional, Union # NOQA
8+
except ImportError:
9+
pass
510

611
from .algorithms import (
712
Algorithm, get_default_algorithms, has_crypto, requires_cryptography # NOQA
@@ -69,8 +74,13 @@ def get_algorithms(self):
6974
"""
7075
return list(self._valid_algs)
7176

72-
def encode(self, payload, key, algorithm='HS256', headers=None,
73-
json_encoder=None):
77+
def encode(self,
78+
payload, # type: Union[Dict, bytes]
79+
key, # type: str
80+
algorithm='HS256', # type: str
81+
headers=None, # type: Optional[Dict]
82+
json_encoder=None # type: Optional[Callable]
83+
):
7484
segments = []
7585

7686
if algorithm is None:
@@ -117,7 +127,12 @@ def encode(self, payload, key, algorithm='HS256', headers=None,
117127

118128
return b'.'.join(segments)
119129

120-
def decode(self, jws, key='', verify=True, algorithms=None, options=None,
130+
def decode(self,
131+
token, # type: str
132+
key='', # type: str
133+
verify=True, # type: bool
134+
algorithms=None, # type: List[str]
135+
options=None, # type: Dict
121136
**kwargs):
122137

123138
merged_options = merge_dict(self.options, options)
@@ -131,7 +146,7 @@ def decode(self, jws, key='', verify=True, algorithms=None, options=None,
131146
DeprecationWarning
132147
)
133148

134-
payload, signing_input, header, signature = self._load(jws)
149+
payload, signing_input, header, signature = self._load(token)
135150

136151
if not verify:
137152
warnings.warn('The verify parameter is deprecated. '

jwt/api_jwt.py

Lines changed: 22 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,11 @@
33
from calendar import timegm
44
from collections import Iterable, Mapping
55
from datetime import datetime, timedelta
6+
try:
7+
# import required by mypy to perform type checking, not used for normal execution
8+
from typing import Callable, Dict, List, Optional, Union # NOQA
9+
except ImportError:
10+
pass
611

712
from .api_jws import PyJWS
813
from .algorithms import Algorithm, get_default_algorithms # NOQA
@@ -20,6 +25,7 @@ class PyJWT(PyJWS):
2025

2126
@staticmethod
2227
def _get_default_options():
28+
# type: () -> Dict[str, bool]
2329
return {
2430
'verify_signature': True,
2531
'verify_exp': True,
@@ -32,8 +38,13 @@ def _get_default_options():
3238
'require_nbf': False
3339
}
3440

35-
def encode(self, payload, key, algorithm='HS256', headers=None,
36-
json_encoder=None):
41+
def encode(self,
42+
payload, # type: Union[Dict, bytes]
43+
key, # type: str
44+
algorithm='HS256', # type: str
45+
headers=None, # type: Optional[Dict]
46+
json_encoder=None # type: Optional[Callable]
47+
):
3748
# Check that we get a mapping
3849
if not isinstance(payload, Mapping):
3950
raise TypeError('Expecting a mapping object, as JWT only supports '
@@ -43,7 +54,7 @@ def encode(self, payload, key, algorithm='HS256', headers=None,
4354
for time_claim in ['exp', 'iat', 'nbf']:
4455
# Convert datetime to a intDate value in known time-format claims
4556
if isinstance(payload.get(time_claim), datetime):
46-
payload[time_claim] = timegm(payload[time_claim].utctimetuple())
57+
payload[time_claim] = timegm(payload[time_claim].utctimetuple()) # type: ignore
4758

4859
json_payload = json.dumps(
4960
payload,
@@ -55,7 +66,12 @@ def encode(self, payload, key, algorithm='HS256', headers=None,
5566
json_payload, key, algorithm, headers, json_encoder
5667
)
5768

58-
def decode(self, jwt, key='', verify=True, algorithms=None, options=None,
69+
def decode(self,
70+
token, # type: str
71+
key='', # type: str
72+
verify=True, # type: bool
73+
algorithms=None, # type: List[str]
74+
options=None, # type: Dict
5975
**kwargs):
6076

6177
if verify and not algorithms:
@@ -66,15 +82,15 @@ def decode(self, jwt, key='', verify=True, algorithms=None, options=None,
6682
DeprecationWarning
6783
)
6884

69-
payload, signing_input, header, signature = self._load(jwt)
85+
payload, _, _, _ = self._load(token)
7086

7187
if options is None:
7288
options = {'verify_signature': verify}
7389
else:
7490
options.setdefault('verify_signature', verify)
7591

7692
decoded = super(PyJWT, self).decode(
77-
jwt, key=key, algorithms=algorithms, options=options, **kwargs
93+
token, key=key, algorithms=algorithms, options=options, **kwargs
7894
)
7995

8096
try:

tox.ini

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,4 +15,4 @@ commands =
1515
deps =
1616
flake8
1717
flake8-import-order
18-
pep8-naming
18+
pep8-naming

0 commit comments

Comments
 (0)