Skip to content

Commit 5d4ef81

Browse files
committed
feat: Add type annotations to parameters and return values
BREAKING CHANGE: Type annotations new in Python3
1 parent f038e10 commit 5d4ef81

18 files changed

+94
-85
lines changed

ibm_cloud_sdk_core/api_exception.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@ class ApiException(Exception):
3333
global_transaction_id (str, optional): Globally unique id the service endpoint has given a transaction.
3434
"""
3535

36-
def __init__(self, code: int, *, message: Optional[str] = None, http_response: Optional[Response] = None):
36+
def __init__(self, code: int, *, message: Optional[str] = None, http_response: Optional[Response] = None) -> None:
3737
# Call the base class constructor with the parameters it needs
3838
super().__init__(message)
3939
self.message = message
@@ -44,14 +44,14 @@ def __init__(self, code: int, *, message: Optional[str] = None, http_response: O
4444
self.global_transaction_id = http_response.headers.get('X-Global-Transaction-ID')
4545
self.message = self.message if self.message else self._get_error_message(http_response)
4646

47-
def __str__(self):
47+
def __str__(self) -> str:
4848
msg = 'Error: ' + str(self.message) + ', Code: ' + str(self.code)
4949
if self.global_transaction_id is not None:
5050
msg += ' , X-global-transaction-id: ' + str(self.global_transaction_id)
5151
return msg
5252

5353
@staticmethod
54-
def _get_error_message(response: Response):
54+
def _get_error_message(response: Response) -> str:
5555
error_message = 'Unknown error'
5656
try:
5757
error_json = response.json()

ibm_cloud_sdk_core/authenticators/authenticator.py

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,17 +19,23 @@
1919
class Authenticator(ABC):
2020
"""This interface defines the common methods and constants associated with an Authenticator implementation."""
2121
@abstractmethod
22-
def authenticate(self, req: dict):
22+
def authenticate(self, req: dict) -> None:
2323
"""Perform the necessary authentication steps for the specified request.
2424
25+
Attributes:
26+
req (dict): Will be modified to contain the appropriate authentication information.
27+
2528
To be implemented by subclasses.
2629
"""
2730
pass
2831

2932
@abstractmethod
30-
def validate(self):
33+
def validate(self) -> None:
3134
"""Validates the current set of configuration information in the Authenticator.
3235
36+
Raises:
37+
ValueError: The configuration information is not valid for service operations.
38+
3339
To be implemented by subclasses.
3440
"""
3541
pass

ibm_cloud_sdk_core/authenticators/basic_authenticator.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -37,14 +37,14 @@ class BasicAuthenticator(Authenticator):
3737
"""
3838
authentication_type = 'basic'
3939

40-
def __init__(self, username: str, password: str):
40+
def __init__(self, username: str, password: str) -> None:
4141
self.username = username
4242
self.password = password
4343
self.validate()
4444
self.authorization_header = self.__construct_basic_auth_header()
4545

4646

47-
def validate(self):
47+
def validate(self) -> None:
4848
"""Validate username and password.
4949
5050
Ensure the username and password are valid for service operations.
@@ -62,13 +62,13 @@ def validate(self):
6262
'Please remove any surrounding {, }, or \" characters.')
6363

6464

65-
def __construct_basic_auth_header(self):
65+
def __construct_basic_auth_header(self) -> str:
6666
authstring = "{0}:{1}".format(self.username, self.password)
6767
base64_authorization = base64.b64encode(authstring.encode('utf-8')).decode('utf-8')
6868
return 'Basic {0}'.format(base64_authorization)
6969

7070

71-
def authenticate(self, req: Request):
71+
def authenticate(self, req: Request) -> None:
7272
"""Add basic authentication information to a request.
7373
7474
Basic Authorization will be added to the request's headers in the form:

ibm_cloud_sdk_core/authenticators/bearer_token_authenticator.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -34,11 +34,11 @@ class BearerTokenAuthenticator(Authenticator):
3434
"""
3535
authentication_type = 'bearerToken'
3636

37-
def __init__(self, bearer_token: str):
37+
def __init__(self, bearer_token: str) -> None:
3838
self.bearer_token = bearer_token
3939
self.validate()
4040

41-
def validate(self):
41+
def validate(self) -> None:
4242
"""Validate the bearer token.
4343
4444
Ensures the bearer token is valid for service operations.
@@ -49,7 +49,7 @@ def validate(self):
4949
if self.bearer_token is None:
5050
raise ValueError('The bearer token shouldn\'t be None.')
5151

52-
def authenticate(self, req: Request):
52+
def authenticate(self, req: Request) -> None:
5353
"""Adds bearer authentication information to the request.
5454
5555
The bearer token will be added to the request's headers in the form:
@@ -63,7 +63,7 @@ def authenticate(self, req: Request):
6363
headers = req.get('headers')
6464
headers['Authorization'] = 'Bearer {0}'.format(self.bearer_token)
6565

66-
def set_bearer_token(self, bearer_token: str):
66+
def set_bearer_token(self, bearer_token: str) -> None:
6767
"""Set a new bearer token to be sent in subsequent service operations.
6868
6969
Args:

ibm_cloud_sdk_core/authenticators/cp4d_authenticator.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -59,13 +59,13 @@ def __init__(self,
5959
*,
6060
disable_ssl_verification: bool = False,
6161
headers: Optional[Dict[str, str]] = None,
62-
proxies: Optional[Dict[str, str]] = None):
62+
proxies: Optional[Dict[str, str]] = None) -> None:
6363
self.token_manager = CP4DTokenManager(
6464
username, password, url, disable_ssl_verification=disable_ssl_verification,
6565
headers=headers, proxies=proxies)
6666
self.validate()
6767

68-
def validate(self):
68+
def validate(self) -> None:
6969
"""Validate username, password, and url for token requests.
7070
7171
Ensures the username, password, and url are not None. Additionally, ensures they do not contain invalid
@@ -91,7 +91,7 @@ def validate(self):
9191
'The url shouldn\'t start or end with curly brackets or quotes. '
9292
'Please remove any surrounding {, }, or \" characters.')
9393

94-
def authenticate(self, req: Request):
94+
def authenticate(self, req: Request) -> None:
9595
"""Adds CP4D authentication information to the request.
9696
9797
The CP4D bearer token will be added to the request's headers in the form:
@@ -106,7 +106,7 @@ def authenticate(self, req: Request):
106106
bearer_token = self.token_manager.get_token()
107107
headers['Authorization'] = 'Bearer {0}'.format(bearer_token)
108108

109-
def set_disable_ssl_verification(self, status: bool = False):
109+
def set_disable_ssl_verification(self, status: bool = False) -> None:
110110
"""Set the flag that indicates whether verification of the server's SSL certificate should be
111111
disabled or not. Defaults to False.
112112
@@ -115,15 +115,15 @@ def set_disable_ssl_verification(self, status: bool = False):
115115
"""
116116
self.token_manager.set_disable_ssl_verification(status)
117117

118-
def set_headers(self, headers: Dict[str, str]):
118+
def set_headers(self, headers: Dict[str, str]) -> None:
119119
"""Default headers to be sent with every CP4D token request.
120120
121121
Args:
122122
headers: The headers to be sent with every CP4D token request.
123123
"""
124124
self.token_manager.set_headers(headers)
125125

126-
def set_proxies(self, proxies: Dict[str, str]):
126+
def set_proxies(self, proxies: Dict[str, str]) -> None:
127127
"""Sets the proxies the token manager will use to communicate with CP4D on behalf of the host.
128128
129129
Args:

ibm_cloud_sdk_core/authenticators/iam_authenticator.py

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -60,16 +60,16 @@ def __init__(self,
6060
url: Optional[str] = None,
6161
client_id: Optional[str] = None,
6262
client_secret: Optional[str] = None,
63-
disable_ssl_verification: Optional[bool] = False,
63+
disable_ssl_verification: bool = False,
6464
headers: Optional[Dict[str, str]] = None,
65-
proxies: Optional[Dict[str, str]] = None):
65+
proxies: Optional[Dict[str, str]] = None) -> None:
6666
self.token_manager = IAMTokenManager(
6767
apikey, url=url, client_id=client_id, client_secret=client_secret,
6868
disable_ssl_verification=disable_ssl_verification,
6969
headers=headers, proxies=proxies)
7070
self.validate()
7171

72-
def validate(self):
72+
def validate(self) -> None:
7373
"""Validates the apikey, client_id, and client_secret for IAM token requests.
7474
7575
Ensure the apikey is not none, and has no bad characters. Additionally, ensure the
@@ -93,7 +93,7 @@ def validate(self):
9393
raise ValueError(
9494
'Both client_id and client_secret should be initialized.')
9595

96-
def authenticate(self, req: Request):
96+
def authenticate(self, req: Request) -> None:
9797
"""Adds IAM authentication information to the request.
9898
9999
The IAM bearer token will be added to the request's headers in the form:
@@ -108,7 +108,7 @@ def authenticate(self, req: Request):
108108
bearer_token = self.token_manager.get_token()
109109
headers['Authorization'] = 'Bearer {0}'.format(bearer_token)
110110

111-
def set_client_id_and_secret(self, client_id: str, client_secret: str):
111+
def set_client_id_and_secret(self, client_id: str, client_secret: str) -> None:
112112
"""Set the client_id and client_secret pair the token manager will use for IAM token requests.
113113
114114
Args:
@@ -121,7 +121,7 @@ def set_client_id_and_secret(self, client_id: str, client_secret: str):
121121
self.token_manager.set_client_id_and_secret(client_id, client_secret)
122122
self.validate()
123123

124-
def set_disable_ssl_verification(self, status: bool = False):
124+
def set_disable_ssl_verification(self, status: bool = False) -> None:
125125
"""Set the flag that indicates whether verification of the server's SSL certificate should be
126126
disabled or not. Defaults to False.
127127
@@ -130,15 +130,15 @@ def set_disable_ssl_verification(self, status: bool = False):
130130
"""
131131
self.token_manager.set_disable_ssl_verification(status)
132132

133-
def set_headers(self, headers: Dict[str, str]):
133+
def set_headers(self, headers: Dict[str, str]) -> None:
134134
"""Headers to be sent with every IAM token request.
135135
136136
Args:
137137
headers: Headers to be sent with every IAM token request.
138138
"""
139139
self.token_manager.set_headers(headers)
140140

141-
def set_proxies(self, proxies: Dict[str, str]):
141+
def set_proxies(self, proxies: Dict[str, str]) -> None:
142142
"""Sets the proxies the token manager will use to communicate with IAM on behalf of the host.
143143
144144
Args:

ibm_cloud_sdk_core/authenticators/no_auth_authenticator.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -20,8 +20,8 @@ class NoAuthAuthenticator(Authenticator):
2020
"""Performs no authentication."""
2121
authentication_type = 'noAuth'
2222

23-
def validate(self):
23+
def validate(self) -> None:
2424
pass
2525

26-
def authenticate(self, req):
26+
def authenticate(self, req) -> None:
2727
pass

ibm_cloud_sdk_core/base_service.py

Lines changed: 12 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -68,7 +68,7 @@ def __init__(self,
6868
*,
6969
service_url: str = None,
7070
authenticator: Authenticator = None,
71-
disable_ssl_verification: bool = False):
71+
disable_ssl_verification: bool = False) -> None:
7272
self.service_url = service_url
7373
self.http_config = {}
7474
self.jar = CookieJar()
@@ -83,18 +83,18 @@ def __init__(self,
8383
'authenticator should be of type Authenticator')
8484

8585
@staticmethod
86-
def _get_system_info():
86+
def _get_system_info() -> str:
8787
return '{0} {1} {2}'.format(
8888
platform.system(), # OS
8989
platform.release(), # OS version
9090
platform.python_version() # Python version
9191
)
9292

93-
def _build_user_agent(self):
93+
def _build_user_agent(self) -> str:
9494
return '{0}-{1} {2}'.format(self.SDK_NAME, __version__,
9595
self._get_system_info())
9696

97-
def configure_service(self, service_name: str):
97+
def configure_service(self, service_name: str) -> None:
9898
"""Look for external configuration of a service. Set service properties.
9999
100100
Try to get config from external sources, with the following priority:
@@ -119,10 +119,10 @@ def configure_service(self, service_name: str):
119119
bool(config.get('DISABLE_SSL'))
120120
)
121121

122-
def _set_user_agent_header(self, user_agent_string=None):
122+
def _set_user_agent_header(self, user_agent_string: str) -> None:
123123
self.user_agent_header = {'User-Agent': user_agent_string}
124124

125-
def set_http_config(self, http_config: dict):
125+
def set_http_config(self, http_config: dict) -> None:
126126
"""Sets the http config dictionary.
127127
128128
The dictionary can contain values that control the timeout, proxies, and etc of HTTP requests.
@@ -141,7 +141,7 @@ def set_http_config(self, http_config: dict):
141141
else:
142142
raise TypeError("http_config parameter must be a dictionary")
143143

144-
def set_disable_ssl_verification(self, status: bool = False):
144+
def set_disable_ssl_verification(self, status: bool = False) -> None:
145145
"""Set the flag that indicates whether verification of
146146
the server's SSL certificate should be disabled or not.
147147
@@ -150,7 +150,7 @@ def set_disable_ssl_verification(self, status: bool = False):
150150
"""
151151
self.disable_ssl_verification = status
152152

153-
def set_service_url(self, service_url: str):
153+
def set_service_url(self, service_url: str) -> None:
154154
"""Set the url the service will make HTTP requests too.
155155
156156
Arguments:
@@ -174,7 +174,7 @@ def get_authenticator(self) -> Authenticator:
174174
"""
175175
return self.authenticator
176176

177-
def set_default_headers(self, headers: Dict[str, str]):
177+
def set_default_headers(self, headers: Dict[str, str]) -> None:
178178
"""Set http headers to be sent in every request.
179179
180180
Arguments:
@@ -339,19 +339,19 @@ def encode_path_vars(*args: str) -> List[str]:
339339
# pylint: disable=protected-access
340340

341341
@staticmethod
342-
def _convert_model(val):
342+
def _convert_model(val: str) -> None:
343343
if isinstance(val, str):
344344
val = json_import.loads(val)
345345
if hasattr(val, "_to_dict"):
346346
return val._to_dict()
347347
return val
348348

349349
@staticmethod
350-
def _convert_list(val):
350+
def _convert_list(val: list) -> None:
351351
if isinstance(val, list):
352352
return ",".join(val)
353353
return val
354354

355355
@staticmethod
356-
def _encode_path_vars(*args):
356+
def _encode_path_vars(*args) -> None:
357357
return (requests.utils.quote(x, safe='') for x in args)

ibm_cloud_sdk_core/cp4d_token_manager.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,7 @@ def __init__(self,
5555
*,
5656
disable_ssl_verification: bool = False,
5757
headers: Optional[Dict[str, str]] = None,
58-
proxies: Optional[Dict[str, str]] = None):
58+
proxies: Optional[Dict[str, str]] = None) -> None:
5959
self.username = username
6060
self.password = password
6161
if url and not self.VALIDATE_AUTH_PATH in url:
@@ -78,7 +78,7 @@ def request_token(self) -> dict:
7878
proxies=self.proxies)
7979
return response
8080

81-
def set_headers(self, headers: Dict[str, str]):
81+
def set_headers(self, headers: Dict[str, str]) -> None:
8282
"""Headers to be sent with every CP4D token request.
8383
8484
Args:
@@ -89,7 +89,7 @@ def set_headers(self, headers: Dict[str, str]):
8989
else:
9090
raise TypeError('headers must be a dictionary')
9191

92-
def set_proxies(self, proxies: Dict[str, str]):
92+
def set_proxies(self, proxies: Dict[str, str]) -> None:
9393
"""Sets the proxies the token manager will use to communicate with CP4D on behalf of the host.
9494
9595
Args:

ibm_cloud_sdk_core/detailed_response.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,7 @@ def __init__(self,
3737
*,
3838
response: Optional[requests.Response] = None,
3939
headers: Optional[Dict[str, str]] = None,
40-
status_code: Optional[int] = None):
40+
status_code: Optional[int] = None) -> None:
4141
self.result = response
4242
self.headers = headers
4343
self.status_code = status_code
@@ -66,7 +66,7 @@ def get_status_code(self) -> int:
6666
"""
6767
return self.status_code
6868

69-
def _to_dict(self):
69+
def _to_dict(self) -> dict:
7070
_dict = {}
7171
if hasattr(self, 'result') and self.result is not None:
7272
_dict['result'] = self.result if isinstance(self.result, (dict, list)) else 'HTTP response'
@@ -76,5 +76,5 @@ def _to_dict(self):
7676
_dict['status_code'] = self.status_code
7777
return _dict
7878

79-
def __str__(self):
79+
def __str__(self) -> str:
8080
return json.dumps(self._to_dict(), indent=4, default=lambda o: o.__dict__)

ibm_cloud_sdk_core/get_authenticator.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,7 @@ def get_authenticator_from_environment(service_name: str) -> Authenticator:
3838
authenticator = __construct_authenticator(config)
3939
return authenticator
4040

41-
def __construct_authenticator(config):
41+
def __construct_authenticator(config: dict) -> Authenticator:
4242
auth_type = config.get('AUTH_TYPE').lower() if config.get('AUTH_TYPE') else 'iam'
4343
authenticator = None
4444

0 commit comments

Comments
 (0)