Skip to content

Commit

Permalink
fix: Improved type-hintings.
Browse files Browse the repository at this point in the history
  • Loading branch information
MPCodeWriter21 committed Jun 27, 2023
1 parent a14f387 commit 137582f
Show file tree
Hide file tree
Showing 11 changed files with 83 additions and 66 deletions.
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,11 @@ Help this project by [Donation](DONATE.md)

Changes
-----------

### 2.5.2

Improved type-hintings.

### 2.5.1

Switched from `setup.py` build system to `pyproject.toml`
Expand Down
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -53,9 +53,9 @@ python setup.py install
Changes
-------

### 2.5.1
### 2.5.2

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

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

Expand Down
6 changes: 4 additions & 2 deletions log21/Argparse.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,11 @@
import sys as _sys
import log21 as _log21
import argparse as _argparse
from typing import Mapping as _Mapping

from gettext import gettext as _gettext
from textwrap import TextWrapper as _TextWrapper
from typing import Mapping as _Mapping, Optional as _Optional

from log21.Colors import get_colors as _gc
from log21.Formatters import DecolorizingFormatter as _Formatter

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


class ColorizingArgumentParser(_argparse.ArgumentParser):
def __init__(self, formatter_class=ColorizingHelpFormatter, colors: _Mapping[str, str] = None, **kwargs):
def __init__(self, formatter_class=ColorizingHelpFormatter, colors: _Optional[_Mapping[str, str]] = None, **kwargs):
self.logger = _log21.Logger('ArgumentParser')
self.colors = colors
super().__init__(formatter_class=formatter_class, **kwargs)
Expand Down
25 changes: 14 additions & 11 deletions log21/Formatters.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,15 @@

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

__all__ = ['ColorizingFormatter', 'DecolorizingFormatter']


class _Formatter(__Formatter):
_level_names: _Mapping[int, str] = {
_level_names: _Dict[int, str] = {
DEBUG: 'DEBUG',
INFO: 'INFO',
WARNING: 'WARNING',
Expand All @@ -21,7 +21,8 @@ class _Formatter(__Formatter):
INPUT: 'INPUT'
}

def __init__(self, fmt: str = None, datefmt: str = None, style: str = '%', level_names: _Mapping[int, str] = None):
def __init__(self, fmt: _Optional[str] = None, datefmt: _Optional[str] = None, style: str = '%',
level_names: _Optional[_Mapping[int, str]] = None):
"""
`level_names` usage:
>>> import log21
Expand Down Expand Up @@ -57,7 +58,7 @@ def level_names(self):
return self._level_names

@level_names.setter
def level_names(self, level_names):
def level_names(self, level_names: _Mapping[int, str]):
if level_names:
if not isinstance(level_names, _Mapping):
raise TypeError('`level_names` must be a Mapping, a dictionary like object!')
Expand Down Expand Up @@ -89,7 +90,7 @@ def format(self, record) -> str:

class ColorizingFormatter(_Formatter):
# Default color values
level_colors: _Mapping[int, _Tuple[str, ...]] = {
level_colors: _Dict[int, _Tuple[str, ...]] = {
DEBUG: ('lightblue',),
INFO: ('green',),
WARNING: ('lightyellow',),
Expand All @@ -102,12 +103,14 @@ class ColorizingFormatter(_Formatter):
name_color = pathname_color = filename_color = module_color = func_name_color = thread_name_color = \
message_color = tuple()

def __init__(self, fmt: str = None, datefmt: str = None, style: str = '%', level_names: _Mapping[int, str] = None,
level_colors: _Mapping[int, _Tuple[str]] = None,
time_color: _Tuple[str, ...] = None, name_color: _Tuple[str, ...] = None,
pathname_color: _Tuple[str, ...] = None, filename_color: _Tuple[str, ...] = None,
module_color: _Tuple[str, ...] = None, func_name_color: _Tuple[str, ...] = None,
thread_name_color: _Tuple[str, ...] = None, message_color: _Tuple[str, ...] = None):
def __init__(self, fmt: _Optional[str] = None, datefmt: _Optional[str] = None, style: str = '%',
level_names: _Optional[_Mapping[int, str]] = None,
level_colors: _Optional[_Mapping[int, _Tuple[str]]] = None,
time_color: _Optional[_Tuple[str, ...]] = None, name_color: _Optional[_Tuple[str, ...]] = None,
pathname_color: _Optional[_Tuple[str, ...]] = None, filename_color: _Optional[_Tuple[str, ...]] = None,
module_color: _Optional[_Tuple[str, ...]] = None, func_name_color: _Optional[_Tuple[str, ...]] = None,
thread_name_color: _Optional[_Tuple[str, ...]] = None,
message_color: _Optional[_Tuple[str, ...]] = None):
super().__init__(fmt=fmt, datefmt=datefmt, style=style, level_names=level_names)
# Checks and sets colors
if level_colors:
Expand Down
9 changes: 5 additions & 4 deletions log21/Logger.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
import logging as _logging

from getpass import getpass as _getpass
from typing import Sequence as _Sequence, Union as _Union
from typing import Sequence as _Sequence, Union as _Union, Optional as _Optional, Callable as _Callable
from logging import raiseExceptions as _raiseExceptions

import log21 as _log21
Expand All @@ -14,7 +14,8 @@


class Logger(_logging.Logger):
def __init__(self, name, level=NOTSET, handlers: _Union[_Sequence[_logging.Handler], _logging.Handler] = None):
def __init__(self, name, level: _Union[int, str]=NOTSET,
handlers: _Optional[_Union[_Sequence[_logging.Handler], _logging.Handler]] = None):
super().__init__(name, level)
self.setLevel(level)
self._progress_bar = None
Expand Down Expand Up @@ -192,13 +193,13 @@ def progress_bar(self):
def progress_bar(self, value: '_log21.ProgressBar'):
self._progress_bar = value

def clear_line(self, length: int = None):
def clear_line(self, length: _Optional[int] = None):
"""
Clear the current line.
:param length: The length of the line to clear.
:return:
"""
for handler in self.handlers:
if hasattr(handler, 'clear_line'):
if isinstance(getattr(handler, 'clear_line', None), _Callable):
handler.clear_line(length)
10 changes: 5 additions & 5 deletions log21/PPrint.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@
import collections as _collections
import dataclasses as _dataclasses

from typing import Mapping as _Mapping, Union as _Union
from pprint import PrettyPrinter as _PrettyPrinter
from typing import Mapping as _Mapping, Optional as _Optional

from log21.Colors import get_colors as _gc

Expand Down Expand Up @@ -75,8 +75,8 @@ class PrettyPrinter(_PrettyPrinter):
'data': _gc('Green')
}

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


def pformat(obj, indent=1, width=80, depth=None, signs_colors: _Mapping[str, str] = None, *, compact=False,
def pformat(obj, indent=1, width=80, depth=None, signs_colors: _Optional[_Mapping[str, str]] = None, *, compact=False,
sort_dicts=True, underscore_numbers=False, **kwargs):
"""Format a Python object into a pretty-printed representation."""
return PrettyPrinter(indent=indent, width=width, depth=depth, compact=compact, signs_colors=signs_colors,
sort_dicts=True, underscore_numbers=False, **kwargs).pformat(obj)
sort_dicts=sort_dicts, underscore_numbers=underscore_numbers, **kwargs).pformat(obj)
16 changes: 9 additions & 7 deletions log21/ProgressBar.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
# log21.ProgressBar.py
# CodeWriter21

from __future__ import annotations

import shutil as _shutil

from typing import Mapping as _Mapping, Any as _Any
from typing import Mapping as _Mapping, Any as _Any, Optional as _Optional

import log21 as _log21
from log21.Logger import Logger as _Logger
Expand Down Expand Up @@ -39,10 +41,10 @@ class ProgressBar:
>>>
"""

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

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

def __call__(self, progress: float, total: float, logger: '_log21.Logger' = None, **kwargs):
def __call__(self, progress: float, total: float, logger: _Optional[_log21.Logger] = None, **kwargs):
if not logger:
logger = self.logger

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

def update(self, progress: float, total: float, logger: '_log21.Logger' = None, **kwargs):
def update(self, progress: float, total: float, logger: _Optional[_log21.Logger] = None, **kwargs):
self(progress, total, logger, **kwargs)
3 changes: 2 additions & 1 deletion log21/StreamHandler.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import shutil as _shutil

from logging import StreamHandler as _StreamHandler
from typing import Optional as _Optional
from log21.Colors import ansi_escape as _ansi_escape, get_colors as _gc, hex_escape as _hex_escape

__all__ = ['IS_WINDOWS', 'ColorizingStreamHandler', 'StreamHandler']
Expand Down Expand Up @@ -59,7 +60,7 @@ def emit(self, record):
self.check_nl(record)
super().emit(record)

def clear_line(self, length: int = None):
def clear_line(self, length: _Optional[int] = None):
"""
Clear the current line.
Expand Down
33 changes: 18 additions & 15 deletions log21/TreePrint.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
# log21.TreePrint.py
# CodeWriter21

from typing import Union as _Union, Mapping as _Mapping, Sequence as _Sequence
from __future__ import annotations

from typing import Union as _Union, Mapping as _Mapping, Sequence as _Sequence, Optional as _Optional, List as _List

from log21.Colors import get_colors as _gc

Expand All @@ -13,8 +15,8 @@ class Node:
'fruit': _gc('LightMagenta'),
}

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

def _get_mode(self, mode=None) -> int:
def _get_mode(self, mode: _Optional[_Union[str, int]] = None) -> int:
if not mode:
mode = self.mode
if isinstance(mode, int):
if mode in [1, 2]:
return mode
if mode in '-_─┌│|└┬├└':
return 1
if mode in '=═╔║╠╚╦╚':
return 2
elif isinstance(mode, str):
if mode in '-_─┌│|└┬├└':
return 1
if mode in '=═╔║╠╚╦╚':
return 2
return -1

def __str__(self, level=0, prefix='', mode=None):
Expand Down Expand Up @@ -88,12 +91,12 @@ def __str__(self, level=0, prefix='', mode=None):
def has_child(self):
return len(self._children) > 0

def add_child(self, child: 'TreePrint.Node'):
def add_child(self, child: TreePrint.Node):
if not isinstance(child, TreePrint.Node):
raise TypeError('`child` must be TreePrint.Node')
self._children.append(child)

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

@staticmethod
def add_to(node: 'TreePrint.Node', data: _Union[_Mapping, _Sequence, str, int], indent: int = 4,
colors: _Mapping[str, str] = None, mode='-'):
def add_to(node: TreePrint.Node, data: _Union[_Mapping, _Sequence, str, int], indent: int = 4,
colors: _Optional[_Mapping[str, str]] = None, mode='-'):
if isinstance(data, _Mapping):
if len(data) == 1:
child = TreePrint.Node(list(data.keys())[0], indent=indent, colors=colors, mode=mode)
Expand Down Expand Up @@ -137,7 +140,7 @@ def add_to(node: 'TreePrint.Node', data: _Union[_Mapping, _Sequence, str, int],
node.add_child(child)

def __init__(self, data: _Union[_Mapping, _Sequence, str, int], indent: int = 4,
colors: _Mapping[str, str] = None, mode='-'):
colors: _Optional[_Mapping[str, str]] = None, mode='-'):
self.indent = indent
self.mode = mode
if isinstance(data, _Mapping):
Expand All @@ -153,7 +156,7 @@ def __init__(self, data: _Union[_Mapping, _Sequence, str, int], indent: int = 4,
else:
self.root = self.Node(str(data), indent=indent, colors=colors)

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

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


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

0 comments on commit 137582f

Please sign in to comment.