Skip to content

Commit 137582f

Browse files
fix: Improved type-hintings.
1 parent a14f387 commit 137582f

11 files changed

Lines changed: 83 additions & 66 deletions

CHANGELOG.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,11 @@ Help this project by [Donation](DONATE.md)
55

66
Changes
77
-----------
8+
9+
### 2.5.2
10+
11+
Improved type-hintings.
12+
813
### 2.5.1
914

1015
Switched from `setup.py` build system to `pyproject.toml`

README.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -53,9 +53,9 @@ python setup.py install
5353
Changes
5454
-------
5555

56-
### 2.5.1
56+
### 2.5.2
5757

58-
Switched from `setup.py` build system to `pyproject.toml`
58+
Improved type-hintings.
5959

6060
[Full CHANGELOG](https://github.com/MPCodeWriter21/log21/blob/master/CHANGELOG.md)
6161

log21/Argparse.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,9 +5,11 @@
55
import sys as _sys
66
import log21 as _log21
77
import argparse as _argparse
8-
from typing import Mapping as _Mapping
8+
99
from gettext import gettext as _gettext
1010
from textwrap import TextWrapper as _TextWrapper
11+
from typing import Mapping as _Mapping, Optional as _Optional
12+
1113
from log21.Colors import get_colors as _gc
1214
from log21.Formatters import DecolorizingFormatter as _Formatter
1315

@@ -477,7 +479,7 @@ def _wrap_chunks(self, chunks): # noqa: C901
477479

478480

479481
class ColorizingArgumentParser(_argparse.ArgumentParser):
480-
def __init__(self, formatter_class=ColorizingHelpFormatter, colors: _Mapping[str, str] = None, **kwargs):
482+
def __init__(self, formatter_class=ColorizingHelpFormatter, colors: _Optional[_Mapping[str, str]] = None, **kwargs):
481483
self.logger = _log21.Logger('ArgumentParser')
482484
self.colors = colors
483485
super().__init__(formatter_class=formatter_class, **kwargs)

log21/Formatters.py

Lines changed: 14 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -3,15 +3,15 @@
33

44
import time as _time
55
from logging import Formatter as __Formatter
6-
from typing import Mapping as _Mapping, Tuple as _Tuple
6+
from typing import Mapping as _Mapping, Tuple as _Tuple, Dict as _Dict, Optional as _Optional
77
from log21.Colors import get_colors as _gc, ansi_escape
88
from log21.Levels import INPUT, CRITICAL, ERROR, WARNING, INFO, DEBUG, PRINT
99

1010
__all__ = ['ColorizingFormatter', 'DecolorizingFormatter']
1111

1212

1313
class _Formatter(__Formatter):
14-
_level_names: _Mapping[int, str] = {
14+
_level_names: _Dict[int, str] = {
1515
DEBUG: 'DEBUG',
1616
INFO: 'INFO',
1717
WARNING: 'WARNING',
@@ -21,7 +21,8 @@ class _Formatter(__Formatter):
2121
INPUT: 'INPUT'
2222
}
2323

24-
def __init__(self, fmt: str = None, datefmt: str = None, style: str = '%', level_names: _Mapping[int, str] = None):
24+
def __init__(self, fmt: _Optional[str] = None, datefmt: _Optional[str] = None, style: str = '%',
25+
level_names: _Optional[_Mapping[int, str]] = None):
2526
"""
2627
`level_names` usage:
2728
>>> import log21
@@ -57,7 +58,7 @@ def level_names(self):
5758
return self._level_names
5859

5960
@level_names.setter
60-
def level_names(self, level_names):
61+
def level_names(self, level_names: _Mapping[int, str]):
6162
if level_names:
6263
if not isinstance(level_names, _Mapping):
6364
raise TypeError('`level_names` must be a Mapping, a dictionary like object!')
@@ -89,7 +90,7 @@ def format(self, record) -> str:
8990

9091
class ColorizingFormatter(_Formatter):
9192
# Default color values
92-
level_colors: _Mapping[int, _Tuple[str, ...]] = {
93+
level_colors: _Dict[int, _Tuple[str, ...]] = {
9394
DEBUG: ('lightblue',),
9495
INFO: ('green',),
9596
WARNING: ('lightyellow',),
@@ -102,12 +103,14 @@ class ColorizingFormatter(_Formatter):
102103
name_color = pathname_color = filename_color = module_color = func_name_color = thread_name_color = \
103104
message_color = tuple()
104105

105-
def __init__(self, fmt: str = None, datefmt: str = None, style: str = '%', level_names: _Mapping[int, str] = None,
106-
level_colors: _Mapping[int, _Tuple[str]] = None,
107-
time_color: _Tuple[str, ...] = None, name_color: _Tuple[str, ...] = None,
108-
pathname_color: _Tuple[str, ...] = None, filename_color: _Tuple[str, ...] = None,
109-
module_color: _Tuple[str, ...] = None, func_name_color: _Tuple[str, ...] = None,
110-
thread_name_color: _Tuple[str, ...] = None, message_color: _Tuple[str, ...] = None):
106+
def __init__(self, fmt: _Optional[str] = None, datefmt: _Optional[str] = None, style: str = '%',
107+
level_names: _Optional[_Mapping[int, str]] = None,
108+
level_colors: _Optional[_Mapping[int, _Tuple[str]]] = None,
109+
time_color: _Optional[_Tuple[str, ...]] = None, name_color: _Optional[_Tuple[str, ...]] = None,
110+
pathname_color: _Optional[_Tuple[str, ...]] = None, filename_color: _Optional[_Tuple[str, ...]] = None,
111+
module_color: _Optional[_Tuple[str, ...]] = None, func_name_color: _Optional[_Tuple[str, ...]] = None,
112+
thread_name_color: _Optional[_Tuple[str, ...]] = None,
113+
message_color: _Optional[_Tuple[str, ...]] = None):
111114
super().__init__(fmt=fmt, datefmt=datefmt, style=style, level_names=level_names)
112115
# Checks and sets colors
113116
if level_colors:

log21/Logger.py

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
import logging as _logging
55

66
from getpass import getpass as _getpass
7-
from typing import Sequence as _Sequence, Union as _Union
7+
from typing import Sequence as _Sequence, Union as _Union, Optional as _Optional, Callable as _Callable
88
from logging import raiseExceptions as _raiseExceptions
99

1010
import log21 as _log21
@@ -14,7 +14,8 @@
1414

1515

1616
class Logger(_logging.Logger):
17-
def __init__(self, name, level=NOTSET, handlers: _Union[_Sequence[_logging.Handler], _logging.Handler] = None):
17+
def __init__(self, name, level: _Union[int, str]=NOTSET,
18+
handlers: _Optional[_Union[_Sequence[_logging.Handler], _logging.Handler]] = None):
1819
super().__init__(name, level)
1920
self.setLevel(level)
2021
self._progress_bar = None
@@ -192,13 +193,13 @@ def progress_bar(self):
192193
def progress_bar(self, value: '_log21.ProgressBar'):
193194
self._progress_bar = value
194195

195-
def clear_line(self, length: int = None):
196+
def clear_line(self, length: _Optional[int] = None):
196197
"""
197198
Clear the current line.
198199
199200
:param length: The length of the line to clear.
200201
:return:
201202
"""
202203
for handler in self.handlers:
203-
if hasattr(handler, 'clear_line'):
204+
if isinstance(getattr(handler, 'clear_line', None), _Callable):
204205
handler.clear_line(length)

log21/PPrint.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -7,8 +7,8 @@
77
import collections as _collections
88
import dataclasses as _dataclasses
99

10-
from typing import Mapping as _Mapping, Union as _Union
1110
from pprint import PrettyPrinter as _PrettyPrinter
11+
from typing import Mapping as _Mapping, Optional as _Optional
1212

1313
from log21.Colors import get_colors as _gc
1414

@@ -75,8 +75,8 @@ class PrettyPrinter(_PrettyPrinter):
7575
'data': _gc('Green')
7676
}
7777

78-
def __init__(self, indent=1, width=80, depth=None, stream=None, signs_colors: _Mapping[str, str] = None, *,
79-
compact=False, sort_dicts=True, underscore_numbers=False, **kwargs):
78+
def __init__(self, indent=1, width=80, depth=None, stream=None, signs_colors: _Optional[_Mapping[str, str]] = None,
79+
*, compact=False, sort_dicts=True, underscore_numbers=False, **kwargs):
8080
super().__init__(indent=indent, width=width, depth=depth, stream=stream, compact=compact, **kwargs)
8181
self._depth = depth
8282
self._indent_per_level = indent
@@ -562,8 +562,8 @@ def _pprint_user_string(self, obj, stream, indent, allowance, context, level):
562562
_dispatch[_collections.UserString.__repr__] = _pprint_user_string
563563

564564

565-
def pformat(obj, indent=1, width=80, depth=None, signs_colors: _Mapping[str, str] = None, *, compact=False,
565+
def pformat(obj, indent=1, width=80, depth=None, signs_colors: _Optional[_Mapping[str, str]] = None, *, compact=False,
566566
sort_dicts=True, underscore_numbers=False, **kwargs):
567567
"""Format a Python object into a pretty-printed representation."""
568568
return PrettyPrinter(indent=indent, width=width, depth=depth, compact=compact, signs_colors=signs_colors,
569-
sort_dicts=True, underscore_numbers=False, **kwargs).pformat(obj)
569+
sort_dicts=sort_dicts, underscore_numbers=underscore_numbers, **kwargs).pformat(obj)

log21/ProgressBar.py

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,11 @@
11
# log21.ProgressBar.py
22
# CodeWriter21
33

4+
from __future__ import annotations
5+
46
import shutil as _shutil
57

6-
from typing import Mapping as _Mapping, Any as _Any
8+
from typing import Mapping as _Mapping, Any as _Any, Optional as _Optional
79

810
import log21 as _log21
911
from log21.Logger import Logger as _Logger
@@ -39,10 +41,10 @@ class ProgressBar:
3941
>>>
4042
"""
4143

42-
def __init__(self, *args, width: int = None, show_percentage: bool = True, prefix: str = '|', suffix: str = '|',
43-
fill: str = '█', empty: str = ' ', format_: str = None, style: str = '%',
44-
new_line_when_complete: bool = True, colors: dict = None, no_color: bool = False,
45-
logger: '_log21.Logger' = _logger, additional_variables: _Mapping[str, _Any] = None):
44+
def __init__(self, *, width: _Optional[int] = None, show_percentage: bool = True, prefix: str = '|',
45+
suffix: str = '|', fill: str = '█', empty: str = ' ', format_: _Optional[str] = None, style: str = '%',
46+
new_line_when_complete: bool = True, colors: _Optional[_Mapping[str, str]] = None, no_color: bool = False,
47+
logger: _log21.Logger = _logger, additional_variables: _Optional[_Mapping[str, _Any]] = None):
4648
"""
4749
:param args: Prevents the use of positional arguments
4850
:param width: The width of the progress bar
@@ -274,11 +276,11 @@ def progress_failed(self, progress: float, total: float, **kwargs):
274276

275277
return '\r' + bar + self.colors['reset-color'] + ('\n' if self.new_line_when_complete else '')
276278

277-
def __call__(self, progress: float, total: float, logger: '_log21.Logger' = None, **kwargs):
279+
def __call__(self, progress: float, total: float, logger: _Optional[_log21.Logger] = None, **kwargs):
278280
if not logger:
279281
logger = self.logger
280282

281283
logger.print(self.get_bar(progress, total, **kwargs), end='')
282284

283-
def update(self, progress: float, total: float, logger: '_log21.Logger' = None, **kwargs):
285+
def update(self, progress: float, total: float, logger: _Optional[_log21.Logger] = None, **kwargs):
284286
self(progress, total, logger, **kwargs)

log21/StreamHandler.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
import shutil as _shutil
77

88
from logging import StreamHandler as _StreamHandler
9+
from typing import Optional as _Optional
910
from log21.Colors import ansi_escape as _ansi_escape, get_colors as _gc, hex_escape as _hex_escape
1011

1112
__all__ = ['IS_WINDOWS', 'ColorizingStreamHandler', 'StreamHandler']
@@ -59,7 +60,7 @@ def emit(self, record):
5960
self.check_nl(record)
6061
super().emit(record)
6162

62-
def clear_line(self, length: int = None):
63+
def clear_line(self, length: _Optional[int] = None):
6364
"""
6465
Clear the current line.
6566

log21/TreePrint.py

Lines changed: 18 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,9 @@
11
# log21.TreePrint.py
22
# CodeWriter21
33

4-
from typing import Union as _Union, Mapping as _Mapping, Sequence as _Sequence
4+
from __future__ import annotations
5+
6+
from typing import Union as _Union, Mapping as _Mapping, Sequence as _Sequence, Optional as _Optional, List as _List
57

68
from log21.Colors import get_colors as _gc
79

@@ -13,8 +15,8 @@ class Node:
1315
'fruit': _gc('LightMagenta'),
1416
}
1517

16-
def __init__(self, value: _Union[str, int], children: list = None, indent: int = 4,
17-
colors: _Mapping[str, str] = None, mode='-'):
18+
def __init__(self, value: _Union[str, int], children: _Optional[_List[TreePrint.Node]] = None, indent: int = 4,
19+
colors: _Optional[_Mapping[str, str]] = None, mode: str='-'):
1820
self.value = str(value)
1921
if children:
2022
self._children = children
@@ -33,16 +35,17 @@ def __init__(self, value: _Union[str, int], children: list = None, indent: int =
3335
if self.mode == -1:
3436
raise ValueError('`mode` must be - or =')
3537

36-
def _get_mode(self, mode=None) -> int:
38+
def _get_mode(self, mode: _Optional[_Union[str, int]] = None) -> int:
3739
if not mode:
3840
mode = self.mode
3941
if isinstance(mode, int):
4042
if mode in [1, 2]:
4143
return mode
42-
if mode in '-_─┌│|└┬├└':
43-
return 1
44-
if mode in '=═╔║╠╚╦╚':
45-
return 2
44+
elif isinstance(mode, str):
45+
if mode in '-_─┌│|└┬├└':
46+
return 1
47+
if mode in '=═╔║╠╚╦╚':
48+
return 2
4649
return -1
4750

4851
def __str__(self, level=0, prefix='', mode=None):
@@ -88,12 +91,12 @@ def __str__(self, level=0, prefix='', mode=None):
8891
def has_child(self):
8992
return len(self._children) > 0
9093

91-
def add_child(self, child: 'TreePrint.Node'):
94+
def add_child(self, child: TreePrint.Node):
9295
if not isinstance(child, TreePrint.Node):
9396
raise TypeError('`child` must be TreePrint.Node')
9497
self._children.append(child)
9598

96-
def get_child(self, value: str = None, index: int = None):
99+
def get_child(self, value: _Optional[str] = None, index: _Optional[int] = None):
97100
if value and index:
98101
raise ValueError('`value` and `index` can not be both set')
99102
if not value and not index:
@@ -106,8 +109,8 @@ def get_child(self, value: str = None, index: int = None):
106109
return self._children[index]
107110

108111
@staticmethod
109-
def add_to(node: 'TreePrint.Node', data: _Union[_Mapping, _Sequence, str, int], indent: int = 4,
110-
colors: _Mapping[str, str] = None, mode='-'):
112+
def add_to(node: TreePrint.Node, data: _Union[_Mapping, _Sequence, str, int], indent: int = 4,
113+
colors: _Optional[_Mapping[str, str]] = None, mode='-'):
111114
if isinstance(data, _Mapping):
112115
if len(data) == 1:
113116
child = TreePrint.Node(list(data.keys())[0], indent=indent, colors=colors, mode=mode)
@@ -137,7 +140,7 @@ def add_to(node: 'TreePrint.Node', data: _Union[_Mapping, _Sequence, str, int],
137140
node.add_child(child)
138141

139142
def __init__(self, data: _Union[_Mapping, _Sequence, str, int], indent: int = 4,
140-
colors: _Mapping[str, str] = None, mode='-'):
143+
colors: _Optional[_Mapping[str, str]] = None, mode='-'):
141144
self.indent = indent
142145
self.mode = mode
143146
if isinstance(data, _Mapping):
@@ -153,7 +156,7 @@ def __init__(self, data: _Union[_Mapping, _Sequence, str, int], indent: int = 4,
153156
else:
154157
self.root = self.Node(str(data), indent=indent, colors=colors)
155158

156-
def add_to_root(self, data: _Union[_Mapping, _Sequence, str, int], colors: _Mapping[str, str] = None):
159+
def add_to_root(self, data: _Union[_Mapping, _Sequence, str, int], colors: _Optional[_Mapping[str, str]] = None):
157160
self.Node.add_to(self.root, data, indent=self.indent, colors=colors, mode=self.mode)
158161

159162
def __str__(self, mode=None):
@@ -163,5 +166,5 @@ def __str__(self, mode=None):
163166

164167

165168
def tree_format(data: _Union[_Mapping, _Sequence, str, int], indent: int = 4, mode='-',
166-
colors: _Mapping[str, str] = None):
169+
colors: _Optional[_Mapping[str, str]] = None):
167170
return str(TreePrint(data, indent=indent, colors=colors, mode=mode))

0 commit comments

Comments
 (0)