Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add some more type hints #1299

Merged
merged 4 commits into from
Oct 3, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions khal/calendar_display.py
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,7 @@ def str_week(
color: str='',
highlight_event_days: bool=False,
locale=None,
bold_for_light_color=True,
bold_for_light_color: bool=True,
) -> str:
"""returns a string representing one week,
if for day == today color is reversed
Expand Down Expand Up @@ -178,9 +178,9 @@ def vertical_month(month: Optional[int]=None,
multiple: str='',
multiple_on_overflow: bool=False,
color: str='',
highlight_event_days=False,
highlight_event_days: bool=False,
locale=None,
bold_for_light_color=True,
bold_for_light_color: bool=True,
) -> List[str]:
"""
returns a list() of str() of weeks for a vertical arranged calendar
Expand Down
4 changes: 2 additions & 2 deletions khal/khalendar/event.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ def __init__(self,
color: Optional[str] = None,
start: Optional[dt.datetime] = None,
end: Optional[dt.datetime] = None,
):
) -> None:
"""
:param start: start datetime of this event instance
:param end: end datetime of this event instance
Expand Down Expand Up @@ -769,7 +769,7 @@ class LocalizedEvent(DatetimeEvent):
see parent
"""

def __init__(self, *args, **kwargs):
def __init__(self, *args, **kwargs) -> None:
super().__init__(*args, **kwargs)
try:
starttz = getattr(self._vevents[self.ref]['DTSTART'].dt, 'tzinfo', None)
Expand Down
2 changes: 1 addition & 1 deletion khal/khalendar/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ class UnsupportedRruleExceptionError(UnsupportedFeatureError):

"""we do not support exceptions that do not delete events yet"""

def __init__(self, message=''):
def __init__(self, message='') -> None:
x = 'This kind of recurrence exception is currently unsupported'
if message:
x += f': {message.strip()}'
Expand Down
10 changes: 5 additions & 5 deletions khal/khalendar/vdir.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ class cached_property:
instances' methods.
'''

def __init__(self, fget, doc=None):
def __init__(self, fget, doc=None) -> None:
self.__name__ = fget.__name__
self.__module__ = fget.__module__
self.__doc__ = doc or fget.__doc__
Expand Down Expand Up @@ -94,7 +94,7 @@ def get_etag_from_file(f) -> str:


class VdirError(IOError):
def __init__(self, *args, **kwargs):
def __init__(self, *args, **kwargs) -> None:
for key, value in kwargs.items():
if getattr(self, key, object()) not in [None, '']: # pragma: no cover
raise TypeError(f'Invalid argument: {key}')
Expand All @@ -120,7 +120,7 @@ class AlreadyExistingError(VdirError):


class Item:
def __init__(self, raw: str):
def __init__(self, raw: str) -> None:
assert isinstance(raw, str)
self.raw = raw

Expand All @@ -145,7 +145,7 @@ class VdirBase:
item_class = Item
default_mode = 0o750

def __init__(self, path: str, fileext: str, encoding: str='utf-8'):
def __init__(self, path: str, fileext: str, encoding: str='utf-8') -> None:
if not os.path.isdir(path):
raise CollectionNotFoundError(path)
self.path = path
Expand Down Expand Up @@ -284,7 +284,7 @@ def set_meta(self, key: str, value: str) -> None:


class Color:
def __init__(self, x: str):
def __init__(self, x: str) -> None:
if not x:
raise ValueError('Color is false-ish.')
if not x.startswith('#'):
Expand Down
27 changes: 14 additions & 13 deletions khal/ui/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,7 @@ def render(self, size, focus=False):


class DateHeader(SelectableText):
def __init__(self, day: dt.date, dateformat: str, conf):
def __init__(self, day: dt.date, dateformat: str, conf) -> None:
"""
:param day: the date that is represented by this DateHeader instance
:param dateformat: format to print `day` in
Expand Down Expand Up @@ -154,7 +154,7 @@ def keypress(self, _, key: str) -> str:


class U_Event(urwid.Text):
def __init__(self, event, conf, delete_status, this_date=None, relative=True):
def __init__(self, event, conf, delete_status, this_date=None, relative=True) -> None:
"""representation of an event in EventList

:param event: the encapsulated event
Expand Down Expand Up @@ -239,7 +239,7 @@ def __init__(
self, *args, parent, conf,
delete_status, toggle_delete_instance, toggle_delete_all,
set_focus_date_callback=None,
**kwargs):
**kwargs) -> None:
self._init: bool = True
self.parent: 'ClassicView' = parent
self.delete_status = delete_status
Expand Down Expand Up @@ -276,7 +276,7 @@ class DListBox(EventListBox):
"""Container for a DayWalker"""
# XXX unfortunate naming, there is also DateListBox

def __init__(self, *args, **kwargs):
def __init__(self, *args, **kwargs) -> None:
dynamic_days = kwargs.pop('dynamic_days', True)
super().__init__(*args, **kwargs)
self._init = dynamic_days
Expand Down Expand Up @@ -352,7 +352,7 @@ class DayWalker(urwid.SimpleFocusListWalker):
"""A list Walker that contains a list of DateListBox objects, each representing
one day and associated events"""

def __init__(self, this_date, eventcolumn, conf, collection, delete_status):
def __init__(self, this_date, eventcolumn, conf, collection, delete_status) -> None:
self.eventcolumn = eventcolumn
self._conf = conf
self.delete_status = delete_status
Expand Down Expand Up @@ -577,11 +577,11 @@ class DateListBox(urwid.ListBox):

selected_date = None

def __init__(self, content, date):
def __init__(self, content, date) -> None:
self.date = date
super().__init__(content)

def __repr__(self):
def __repr__(self) -> str:
return f'<DateListBox {self.date}>'

__str__ = __repr__
Expand Down Expand Up @@ -633,7 +633,7 @@ class EventColumn(urwid.WidgetWrap):
Handles modifying events, showing events' details and editing them
"""

def __init__(self, elistbox, pane):
def __init__(self, elistbox, pane) -> None:
self.pane = pane
self._conf = pane._conf
self.divider = urwid.Divider('─')
Expand Down Expand Up @@ -955,7 +955,7 @@ def render(self, a, focus):
class EventDisplay(urwid.WidgetWrap):
"""A widget showing one Event()'s details """

def __init__(self, conf, event, collection=None):
def __init__(self, conf, event, collection=None) -> None:
self._conf = conf
self.collection = collection
self.event = event
Expand Down Expand Up @@ -1017,7 +1017,7 @@ def __init__(self, conf, event, collection=None):
class SearchDialog(urwid.WidgetWrap):
"""A Search Dialog Widget"""

def __init__(self, search_func, abort_func):
def __init__(self, search_func, abort_func) -> None:

class Search(Edit):

Expand Down Expand Up @@ -1052,7 +1052,7 @@ class ClassicView(Pane):
on the right
"""

def __init__(self, collection, conf=None, title: str='', description: str=''):
def __init__(self, collection, conf=None, title: str='', description: str='') -> None:
self.init = True
# Will be set when opening the view inside a Window
self.window = None
Expand Down Expand Up @@ -1156,8 +1156,9 @@ def search(self):
height=None)
self.window.open(overlay)

def _search(self, search_term: str):
def _search(self, search_term: str) -> None:
"""search for events matching `search_term"""
assert self.window is not None
self.window.backtrack()
events = sorted(self.collection.search(search_term))
event_list = []
Expand Down Expand Up @@ -1311,7 +1312,7 @@ def get_prefix(self, level):
else:
return 'DEBUG'

def format(self, record):
def format(self, record) -> str:
return f'{self.get_prefix(record.levelno)}: {record.msg}'

class HeaderFormatter(LogPaneFormatter):
Expand Down
28 changes: 15 additions & 13 deletions khal/ui/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,12 @@
"""this module should contain classes that are specific to ikhal, more
general widgets should go in widgets.py"""

from __future__ import annotations

import logging
import threading
import time
from typing import Callable, List, Optional, Tuple, Union
from typing import Callable

import urwid

Expand All @@ -39,7 +41,7 @@ class Pane(urwid.WidgetWrap):

"""An abstract Pane to be used in a Window object."""

def __init__(self, widget, title=None, description=None):
def __init__(self, widget, title=None, description=None) -> None:
self.widget = widget
urwid.WidgetWrap.__init__(self, widget)
self._title = title or ''
Expand All @@ -58,14 +60,12 @@ def selectable(self):
def description(self):
return self._description

def dialog(self, text, buttons):
def dialog(self, text: str, buttons: list[tuple[str, Callable]]) -> None:
"""Open a dialog box.

:param text: Text to appear as the body of the Dialog box
:type text: str
:param buttons: list of tuples button labels and functions to call
when the button is pressed
:type buttons: list(str, callable)
"""
lines = [urwid.Text(line) for line in text.splitlines()]

Expand All @@ -76,12 +76,13 @@ def dialog(self, text, buttons):
lines.append(buttons)
content = urwid.LineBox(urwid.Pile(lines))
overlay = urwid.Overlay(content, self, 'center', ('relative', 70), ('relative', 70), None)
assert self.window is not None
self.window.open(overlay)

def scrollable_dialog(self,
text: Union[str, List[urwid.Text]],
buttons: Optional[List[Tuple[str, Callable]]]=None,
title="Press `ESC` to close this window",
text: str | list[urwid.Text],
buttons: list[tuple[str, Callable]] | None = None,
title: str = "Press `ESC` to close this window",
) -> None:
"""Open a scrollable dialog box.

Expand All @@ -107,6 +108,7 @@ def scrollable_dialog(self,
)
overlay = urwid.Overlay(
over, self, 'center', ('relative', 70), 'middle', ('relative', 70), None)
assert self.window is not None
self.window.open(overlay)

def keypress(self, size, key):
Expand Down Expand Up @@ -148,9 +150,9 @@ class Window(urwid.Frame):
to carry data between them.
"""

def __init__(self, footer='', quit_keys=None):
def __init__(self, footer='', quit_keys=None) -> None:
quit_keys = quit_keys or ['q']
self._track = []
self._track: list[urwid.Overlay] = []

header = urwid.AttrWrap(urwid.Text(''), 'header')
footer = urwid.AttrWrap(urwid.Text(footer), 'footer')
Expand All @@ -167,7 +169,7 @@ def alert(message):
self._alert_daemon.start()
self.alert = self._alert_daemon.alert
self.loop = None
self._log = []
self._log: list[str] = []
self._header_is_warning = False

def open(self, pane, callback=None):
Expand Down Expand Up @@ -215,7 +217,7 @@ def _update(self, pane):
self.set_body(pane)
self.clear_header()

def log(self, record):
def log(self, record: str):
self._log.append(record)

def _get_current_pane(self):
Expand Down Expand Up @@ -248,7 +250,7 @@ def update_header(self, alert=None, warn=False):


class AlertDaemon(threading.Thread):
def __init__(self, set_msg_func):
def __init__(self, set_msg_func) -> None:
threading.Thread.__init__(self)
self._set_msg_func = set_msg_func
self.daemon = True
Expand Down
10 changes: 5 additions & 5 deletions khal/ui/calendarwidget.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ class DatePart(urwid.Text):

"""used in the Date widget (single digit)"""

def __init__(self, digit: str):
def __init__(self, digit: str) -> None:
super().__init__(digit)

@classmethod
Expand All @@ -82,7 +82,7 @@ class Date(urwid.WidgetWrap):

"""used in the main calendar for dates (a number)"""

def __init__(self, date: dt.date, get_styles: GetStylesSignature):
def __init__(self, date: dt.date, get_styles: GetStylesSignature) -> None:
dstr = str(date.day).rjust(2)
self.halves = [urwid.AttrMap(DatePart(dstr[:1]), None, None),
urwid.AttrMap(DatePart(dstr[1:]), None, None)]
Expand Down Expand Up @@ -142,7 +142,7 @@ def __init__(self,
on_press: OnPressType,
keybindings: Dict[str, List[str]],
get_styles: GetStylesSignature,
**kwargs):
**kwargs) -> None:
self.on_date_change = on_date_change
self.on_press = on_press
self.keybindings = keybindings
Expand Down Expand Up @@ -236,7 +236,7 @@ class CListBox(urwid.ListBox):
it should contain a `CalendarWalker` instance which it autoextends on
rendering, if needed """

def __init__(self, walker: 'CalendarWalker'):
def __init__(self, walker: 'CalendarWalker') -> None:
self._init: bool = True
self.keybindings = walker.keybindings
self.on_press = walker.on_press
Expand Down Expand Up @@ -595,7 +595,7 @@ def __init__(self,
monthdisplay: Literal['firstday', 'firstfullweek']='firstday',
get_styles: Optional[GetStylesSignature]=None,
initial: Optional[dt.date]=None,
):
) -> None:
"""A calendar widget that can be used in urwid applications

:param on_date_change: a function that is called every time the selected
Expand Down
Loading