Skip to content

Commit

Permalink
Disable implicit introduction of Optional via default parameter.
Browse files Browse the repository at this point in the history
Citing PEP 484 (Type Hints):

    A past version of this PEP allowed type checkers to assume an optional
    type when the default value is None, as in this code:

        def handle_employee(e: Employee = None): ...

    This would have been treated as equivalent to:

        def handle_employee(e: Optional[Employee] = None) -> None: ...

    This is no longer the recommended behavior.  Type checkers should move
    towards requiring the optional type to be made explicit.

Currently mypy has the old behavior as the default, but this will probably
changed soon, see python/mypy#9091.

Change-Id: I7349f50345ba98337b821a5a2006c60dfe342341
  • Loading branch information
spt29 committed Aug 6, 2020
1 parent d2dbd09 commit 9d65a6f
Show file tree
Hide file tree
Showing 30 changed files with 86 additions and 83 deletions.
6 changes: 3 additions & 3 deletions cmk/base/api/agent_based/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -150,9 +150,9 @@ def check_levels(
*,
levels_upper=None, # tpye: Optional[Tuple[float, float]]
levels_lower=None, # tpye: Optional[Tuple[float, float]]
metric_name: str = None,
render_func: Callable[[float], str] = None,
label: str = None,
metric_name: Optional[str] = None,
render_func: Optional[Callable[[float], str]] = None,
label: Optional[str] = None,
boundaries: Optional[Tuple[Optional[float], Optional[float]]] = None,
) -> Generator[Union[Result, Metric], None, None]:
"""Generic function for checking a value against levels.
Expand Down
4 changes: 2 additions & 2 deletions cmk/base/check_api_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,8 +36,8 @@ class Service:
def __init__(self,
item: Item,
parameters: LegacyCheckParameters = None,
service_labels: DiscoveredServiceLabels = None,
host_labels: DiscoveredHostLabels = None) -> None:
service_labels: Optional[DiscoveredServiceLabels] = None,
host_labels: Optional[DiscoveredHostLabels] = None) -> None:
self.item = item
self.parameters = parameters
self.service_labels = service_labels or DiscoveredServiceLabels()
Expand Down
2 changes: 1 addition & 1 deletion cmk/base/check_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ def __init__(
item: Item,
description: str,
parameters: LegacyCheckParameters,
service_labels: DiscoveredServiceLabels = None,
service_labels: Optional[DiscoveredServiceLabels] = None,
) -> None:
self._check_plugin_name = check_plugin_name
self._item = item
Expand Down
7 changes: 4 additions & 3 deletions cmk/base/crash_reporting.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,9 +35,10 @@ def type(cls) -> str:
return "base"

@classmethod
def from_exception(cls,
details: Dict = None,
type_specific_attributes: Dict = None) -> crash_reporting.ABCCrashReport:
def from_exception(
cls,
details: Optional[Dict] = None,
type_specific_attributes: Optional[Dict] = None) -> crash_reporting.ABCCrashReport:
return super(CMKBaseCrashReport, cls).from_exception(details={
"argv": sys.argv,
"env": dict(os.environ),
Expand Down
12 changes: 5 additions & 7 deletions cmk/base/modes/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -201,13 +201,13 @@ class Option:
def __init__(self,
long_option: str,
short_help: str,
short_option: str = None,
short_option: Optional[str] = None,
argument: bool = False,
argument_descr: str = None,
argument_conv: ConvertFunction = None,
argument_descr: Optional[str] = None,
argument_conv: Optional[ConvertFunction] = None,
argument_optional: bool = False,
count: bool = False,
handler_function: OptionFunction = None) -> None:
handler_function: Optional[OptionFunction] = None) -> None:
# TODO: This disable is needed because of a pylint bug. Remove one day.
super(Option, self).__init__() # pylint: disable=bad-super-call
self.long_option = long_option
Expand Down Expand Up @@ -290,14 +290,12 @@ def __init__(self,
short_option: Optional[OptionName] = None,
argument: bool = False,
argument_descr: Optional[str] = None,
argument_conv: ConvertFunction = None,
argument_conv: Optional[ConvertFunction] = None,
argument_optional: bool = False,
long_help: Optional[List[str]] = None,
needs_config: bool = True,
needs_checks: bool = True,
sub_options: Optional[List[Option]] = None) -> None:
# TODO: This disable is needed because of a pylint bug. Remove one day.
# pylint: disable=bad-super-call
super(Mode, self).__init__(long_option,
short_help,
short_option,
Expand Down
4 changes: 2 additions & 2 deletions cmk/ec/actions.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
import os
import subprocess
import time
from typing import Any, Dict, Set
from typing import Any, Dict, Optional, Set

import cmk.utils.debug
import cmk.utils.defines
Expand Down Expand Up @@ -262,7 +262,7 @@ def to_string(v: Any) -> str:
def do_notify(event_server: Any,
logger: Logger,
event: Any,
username: bool = None,
username: Optional[bool] = None,
is_cancelling: bool = False) -> None:
if _core_has_notifications_disabled(event, logger):
return
Expand Down
2 changes: 1 addition & 1 deletion cmk/gui/background_job.py
Original file line number Diff line number Diff line change
Expand Up @@ -271,7 +271,7 @@ class BackgroundJob:
# TODO: Make this an abstract property
job_prefix = "unnamed-job"

def __init__(self, job_id: str, logger: logging.Logger = None, **kwargs: Any) -> None:
def __init__(self, job_id: str, logger: Optional[logging.Logger] = None, **kwargs: Any) -> None:
super(BackgroundJob, self).__init__()
self._job_id = job_id
self._job_base_dir = BackgroundJobDefines.base_dir
Expand Down
2 changes: 1 addition & 1 deletion cmk/gui/breadcrumb.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@


class Breadcrumb(MutableSequence[BreadcrumbItem]):
def __init__(self, items: Iterable[BreadcrumbItem] = None):
def __init__(self, items: Optional[Iterable[BreadcrumbItem]] = None):
super().__init__()
self._items: List[BreadcrumbItem] = list(items) if items else []

Expand Down
2 changes: 1 addition & 1 deletion cmk/gui/forms.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ def edit_dictionaries(dictionaries: 'List[Tuple[str, Union[Transform, Dictionary
validate: Optional[Callable[[Any], None]] = None,
buttontext: Optional[str] = None,
title: Optional[str] = None,
buttons: List[Tuple[str, str, str]] = None,
buttons: Optional[List[Tuple[str, str, str]]] = None,
method: str = "GET",
preview: bool = False,
varprefix: str = "",
Expand Down
14 changes: 8 additions & 6 deletions cmk/gui/htmllib.py
Original file line number Diff line number Diff line change
Expand Up @@ -1812,7 +1812,7 @@ def body_end(self) -> None:

def begin_form(self,
name: str,
action: str = None,
action: Optional[str] = None,
method: str = "GET",
onsubmit: Optional[str] = None,
add_transid: bool = True) -> None:
Expand Down Expand Up @@ -1857,7 +1857,9 @@ def add_form_var(self, varname: str) -> None:
# field to the form - *if* they are not used in any input
# field. (this is the reason why you must not add any further
# input fields after this method has been called).
def hidden_fields(self, varlist: List[str] = None, add_action_vars: bool = False) -> None:
def hidden_fields(self,
varlist: Optional[List[str]] = None,
add_action_vars: bool = False) -> None:
if varlist is not None:
for var in varlist:
self.hidden_field(var, self.request.var(var, ""))
Expand All @@ -1870,7 +1872,7 @@ def hidden_fields(self, varlist: List[str] = None, add_action_vars: bool = False
def hidden_field(self,
var: str,
value: HTMLTagValue,
id_: str = None,
id_: Optional[str] = None,
add_var: bool = False,
class_: CSSSpec = None) -> None:
self.write_html(
Expand All @@ -1879,7 +1881,7 @@ def hidden_field(self,
def render_hidden_field(self,
var: str,
value: HTMLTagValue,
id_: str = None,
id_: Optional[str] = None,
add_var: bool = False,
class_: CSSSpec = None) -> HTML:
if value is None:
Expand Down Expand Up @@ -2102,7 +2104,7 @@ def text_input(self,
cssclass: str = "text",
size: Union[None, str, int] = None,
label: Optional[str] = None,
id_: str = None,
id_: Optional[str] = None,
submit: Optional[str] = None,
try_max_width: bool = False,
read_only: bool = False,
Expand Down Expand Up @@ -2224,7 +2226,7 @@ def password_input(self,
cssclass: str = "text",
size: Union[None, str, int] = None,
label: Optional[str] = None,
id_: str = None,
id_: Optional[str] = None,
submit: Optional[str] = None,
try_max_width: bool = False,
read_only: bool = False,
Expand Down
2 changes: 1 addition & 1 deletion cmk/gui/plugins/dashboard/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -581,7 +581,7 @@ def _transform_builtin_dashboards() -> None:
def copy_view_into_dashlet(dashlet: DashletConfig,
nr: DashletId,
view_name: str,
add_context: VisualContext = None,
add_context: Optional[VisualContext] = None,
load_from_all_views: bool = False) -> None:
permitted_views = get_permitted_views()

Expand Down
2 changes: 1 addition & 1 deletion cmk/gui/plugins/openapi/restful_objects/constructors.py
Original file line number Diff line number Diff line change
Expand Up @@ -679,7 +679,7 @@ def collection_item(
)


def serve_json(data: Serializable, profile: Dict[str, str] = None) -> Response:
def serve_json(data: Serializable, profile: Optional[Dict[str, str]] = None) -> Response:
content_type = 'application/json'
if profile is not None:
content_type += ';profile="%s"' % (profile,)
Expand Down
4 changes: 2 additions & 2 deletions cmk/gui/plugins/openapi/restful_objects/decorators.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,14 +68,14 @@ def _reduce_to_primitives(
def endpoint_schema(path: str,
name: EndpointName,
method: HTTPMethod = 'get',
parameters: Sequence[AnyParameterAndReference] = None,
parameters: Optional[Sequence[AnyParameterAndReference]] = None,
content_type: str = 'application/json',
output_empty: bool = False,
response_schema: ResponseSchema = None,
request_schema: RequestSchema = None,
request_body_required: bool = True,
error_schema: Schema = ApiError,
etag: ETagBehaviour = None,
etag: Optional[ETagBehaviour] = None,
will_do_redirects: bool = False,
**options: dict):
"""Mark the function as a REST-API endpoint.
Expand Down
41 changes: 20 additions & 21 deletions cmk/gui/plugins/openapi/restful_objects/type_defs.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,7 @@
# Copyright (C) 2020 tribe29 GmbH - License: GNU General Public License v2
# This file is part of Checkmk (https://checkmk.com). It is subject to the terms and
# conditions defined in the file COPYING, which is part of this source code package.
from typing import Callable, Dict, Any, Optional, Sequence, Tuple, Type, Union, List, Literal, \
TypedDict
from typing import Any, Callable, Dict, List, Literal, Optional, Sequence, Tuple, Type, TypedDict, Union

from marshmallow import Schema # type: ignore[import]

Expand Down Expand Up @@ -133,15 +132,15 @@


def _translate_to_openapi_keys(
name: str = None,
location: LocationType = None,
name: Optional[str] = None,
location: Optional[LocationType] = None,
description: Optional[str] = None,
required: bool = None,
example: str = None,
allow_emtpy: bool = None,
schema_type: OpenAPISchemaType = None,
required: Optional[bool] = None,
example: Optional[str] = None,
allow_emtpy: Optional[bool] = None,
schema_type: Optional[OpenAPISchemaType] = None,
schema_string_pattern: Optional[str] = None,
schema_string_format: str = None,
schema_string_format: Optional[str] = None,
schema_num_minimum: Optional[int] = None,
schema_num_maximum: Optional[int] = None,
):
Expand Down Expand Up @@ -201,15 +200,15 @@ def __init__(self, *seq, **kwargs):

def __call__(
self,
name: str = None,
description: str = None,
location: LocationType = None,
required: bool = None,
allow_empty: bool = None,
example: str = None,
schema_type: OpenAPISchemaType = None,
schema_string_pattern: str = None,
schema_string_format: str = None,
name: Optional[str] = None,
description: Optional[str] = None,
location: Optional[LocationType] = None,
required: Optional[bool] = None,
allow_empty: Optional[bool] = None,
example: Optional[str] = None,
schema_type: Optional[OpenAPISchemaType] = None,
schema_string_pattern: Optional[str] = None,
schema_string_format: Optional[str] = None,
schema_num_minimum: Optional[int] = None,
schema_num_maximum: Optional[int] = None,
):
Expand Down Expand Up @@ -265,10 +264,10 @@ def create(
description: Optional[str] = None,
required: bool = True,
allow_emtpy: bool = False,
example: str = None,
schema_type: OpenAPISchemaType = 'string',
example: Optional[str] = None,
schema_type: Optional[OpenAPISchemaType] = 'string',
schema_string_pattern: Optional[str] = None,
schema_string_format: str = None,
schema_string_format: Optional[str] = None,
schema_num_minimum: Optional[int] = None,
schema_num_maximum: Optional[int] = None,
) -> 'ParamDict':
Expand Down
3 changes: 2 additions & 1 deletion cmk/gui/plugins/userdb/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -207,7 +207,8 @@ def load_connection_config(lock: bool = False) -> List[UserConnectionSpec]:
return store.load_from_mk_file(filename, "user_connections", default=[], lock=lock)


def save_connection_config(connections: List[UserConnectionSpec], base_dir: str = None) -> None:
def save_connection_config(connections: List[UserConnectionSpec],
base_dir: Optional[str] = None) -> None:
if not base_dir:
base_dir = _multisite_dir()
store.mkdir(base_dir)
Expand Down
2 changes: 1 addition & 1 deletion cmk/gui/plugins/views/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -1146,7 +1146,7 @@ def get_graph_timerange_from_painter_options() -> TimeRange:
def paint_age(timestamp: Timestamp,
has_been_checked: bool,
bold_if_younger_than: int,
mode: str = None,
mode: Optional[str] = None,
what: str = 'past') -> CellSpec:
if not has_been_checked:
return "age", "-"
Expand Down
5 changes: 3 additions & 2 deletions cmk/gui/userdb.py
Original file line number Diff line number Diff line change
Expand Up @@ -468,7 +468,7 @@ def declare_user_attribute(name: str,
user_editable: bool = True,
permission: Optional[str] = None,
show_in_table: bool = False,
topic: str = None,
topic: Optional[str] = None,
add_custom_macro: bool = False,
domain: str = "multisite",
from_config: bool = False) -> None:
Expand Down Expand Up @@ -794,7 +794,8 @@ def _cleanup_old_user_profiles(updated_profiles: Users) -> None:
os.unlink(entry + '/' + to_delete)


def write_contacts_and_users_file(profiles: Users, custom_default_config_dir: str = None) -> None:
def write_contacts_and_users_file(profiles: Users,
custom_default_config_dir: Optional[str] = None) -> None:
non_contact_keys = _non_contact_keys()
multisite_keys = _multisite_keys()
updated_profiles = _add_custom_macro_attributes(profiles)
Expand Down
Loading

0 comments on commit 9d65a6f

Please sign in to comment.