Skip to content

Commit 4262c10

Browse files
feat: Added argument to function with will be passed to the formatter
1 parent ee99e36 commit 4262c10

11 files changed

Lines changed: 84 additions & 65 deletions

File tree

CHANGES-LOG.md renamed to CHANGELOG.md

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,14 @@ log21
33

44
Help this project by [Donation](DONATE.md)
55

6-
Changes log
6+
Changes
77
-----------
8+
### 2.5.0
9+
10+
Added `level_colors` argument to `log21.get_logger` function with will be passed to the formatter and allows
11+
user to set custom level colors while making a new logger.
12+
Also changed most `Dict` type hints to be `Mapping` and `list` to `Sequence` to make the functions more general
13+
and less strict.
814

915
### 2.4.7
1016

LICENSE.txt

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -186,7 +186,7 @@
186186
same "printed page" as the copyright notice for easier
187187
identification within third-party archives.
188188

189-
Copyright [2021-2022] [CodeWriter21]
189+
Copyright [2021-2023] [CodeWriter21]
190190

191191
Licensed under the Apache License, Version 2.0 (the "License");
192192
you may not use this file except in compliance with the License.

README.md

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

56-
### 2.4.7
56+
### 2.5.0
5757

58-
Added `extra_values` argument to `CrashReporter.Formatter` which will let you pass extra static or dynamic values to the
59-
report formatter.
60-
They can be used in the format string. For dynamic values you can pass a function that takes no
61-
arguments as the value.
58+
Added `level_colors` argument to `log21.get_logger` function with will be passed to the formatter and allows
59+
user to set custom level colors while making a new logger.
6260

63-
[Full Changes Log](https://github.com/MPCodeWriter21/log21/blob/master/CHANGES-LOG.md)
61+
[Full CHANGELOG](https://github.com/MPCodeWriter21/log21/blob/master/CHANGELOG.md)
6462

6563

6664
Usage Examples:

log21/Argparse.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
import sys as _sys
66
import log21 as _log21
77
import argparse as _argparse
8-
from typing import Dict as _Dict
8+
from typing import Mapping as _Mapping
99
from gettext import gettext as _gettext
1010
from textwrap import TextWrapper as _TextWrapper
1111
from log21.Colors import get_colors as _gc
@@ -27,7 +27,7 @@ class ColorizingHelpFormatter(_argparse.HelpFormatter):
2727
'choices': 'LightGreen'
2828
}
2929

30-
def __init__(self, prog, indent_increment=2, max_help_position=24, width=None, colors: _Dict[str, str] = None):
30+
def __init__(self, prog, indent_increment=2, max_help_position=24, width=None, colors: _Mapping[str, str] = None):
3131
super().__init__(prog, indent_increment, max_help_position, width)
3232
if colors:
3333
for key, value in colors.items():
@@ -477,7 +477,7 @@ def _wrap_chunks(self, chunks): # noqa: C901
477477

478478

479479
class ColorizingArgumentParser(_argparse.ArgumentParser):
480-
def __init__(self, formatter_class=ColorizingHelpFormatter, colors: _Dict[str, str] = None, **kwargs):
480+
def __init__(self, formatter_class=ColorizingHelpFormatter, colors: _Mapping[str, str] = None, **kwargs):
481481
self.logger = _log21.Logger('ArgumentParser')
482482
self.colors = colors
483483
super().__init__(formatter_class=formatter_class, **kwargs)

log21/CrashReporter/Formatters.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
import traceback
55

66
from datetime import datetime as _datetime
7-
from typing import Dict as _Dict, Union as _Union, Callable as _Callable, Any as _Any
7+
from typing import Mapping as _Mapping, Union as _Union, Callable as _Callable, Any as _Any
88

99
__all__ = ['Formatter', 'CONSOLE_REPORTER_FORMAT', 'FILE_REPORTER_FORMAT', 'EMAIL_REPORTER_FORMAT']
1010

@@ -23,7 +23,7 @@
2323

2424
class Formatter:
2525
def __init__(self, format_: str, style: str = '%', datefmt: str = '%Y-%m-%d %H:%M:%S',
26-
extra_values: _Dict[str, _Union[str, _Callable, _Any]] = None):
26+
extra_values: _Mapping[str, _Union[str, _Callable, _Any]] = None):
2727
self._format = format_
2828

2929
if style in ['%', '{']:

log21/Formatters.py

Lines changed: 18 additions & 18 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 Dict as _Dict, Tuple as _Tuple
6+
from typing import Mapping as _Mapping, Tuple as _Tuple
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: _Dict[int, str] = {
14+
_level_names: _Mapping[int, str] = {
1515
DEBUG: 'DEBUG',
1616
INFO: 'INFO',
1717
WARNING: 'WARNING',
@@ -21,7 +21,7 @@ class _Formatter(__Formatter):
2121
INPUT: 'INPUT'
2222
}
2323

24-
def __init__(self, fmt: str = None, datefmt: str = None, style: str = '%', level_names: _Dict[int, str] = None):
24+
def __init__(self, fmt: str = None, datefmt: str = None, style: str = '%', level_names: _Mapping[int, str] = None):
2525
"""
2626
`level_names` usage:
2727
>>> import log21
@@ -59,8 +59,8 @@ def level_names(self):
5959
@level_names.setter
6060
def level_names(self, level_names):
6161
if level_names:
62-
if not isinstance(level_names, _Dict):
63-
raise TypeError('`level_names` must be a dictionary!')
62+
if not isinstance(level_names, _Mapping):
63+
raise TypeError('`level_names` must be a Mapping, a dictionary like object!')
6464
self._level_names = level_names
6565
else:
6666
self._level_names = dict()
@@ -89,7 +89,7 @@ def format(self, record) -> str:
8989

9090
class ColorizingFormatter(_Formatter):
9191
# Default color values
92-
level_colors: _Dict[int, _Tuple[str, ...]] = {
92+
level_colors: _Mapping[int, _Tuple[str, ...]] = {
9393
DEBUG: ('lightblue',),
9494
INFO: ('green',),
9595
WARNING: ('lightyellow',),
@@ -102,49 +102,49 @@ class ColorizingFormatter(_Formatter):
102102
name_color = pathname_color = filename_color = module_color = func_name_color = thread_name_color = \
103103
message_color = tuple()
104104

105-
def __init__(self, fmt: str = None, datefmt: str = None, style: str = '%', level_names: _Dict[int, str] = None,
106-
level_colors: _Dict[int, _Tuple[str]] = None,
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,
107107
time_color: _Tuple[str, ...] = None, name_color: _Tuple[str, ...] = None,
108108
pathname_color: _Tuple[str, ...] = None, filename_color: _Tuple[str, ...] = None,
109109
module_color: _Tuple[str, ...] = None, func_name_color: _Tuple[str, ...] = None,
110110
thread_name_color: _Tuple[str, ...] = None, message_color: _Tuple[str, ...] = None):
111111
super().__init__(fmt=fmt, datefmt=datefmt, style=style, level_names=level_names)
112112
# Checks and sets colors
113113
if level_colors:
114-
if type(level_colors) is not dict:
115-
raise TypeError('`level_colors` must be a dictionary!')
114+
if not isinstance(level_colors, _Mapping):
115+
raise TypeError('`level_colors` must be a dictionary like object!')
116116
for level, color in level_colors.items():
117117
self.level_colors[level] = (_gc(*color),)
118118
if time_color:
119-
if type(time_color) is not tuple:
119+
if not isinstance(time_color, tuple):
120120
raise TypeError('`time_color` must be a tuple!')
121121
self.time_color = time_color
122122
if name_color:
123-
if type(name_color) is not tuple:
123+
if not isinstance(name_color, tuple):
124124
raise TypeError('`name_color` must be a tuple!')
125125
self.name_color = name_color
126126
if pathname_color:
127-
if type(pathname_color) is not tuple:
127+
if not isinstance(pathname_color, tuple):
128128
raise TypeError('`pathname_color` must be a tuple!')
129129
self.pathname_color = pathname_color
130130
if filename_color:
131-
if type(filename_color) is not tuple:
131+
if not isinstance(filename_color, tuple):
132132
raise TypeError('`filename_color` must be a tuple!')
133133
self.filename_color = filename_color
134134
if module_color:
135-
if type(module_color) is not tuple:
135+
if not isinstance(module_color, tuple):
136136
raise TypeError('`module_color` must be a tuple!')
137137
self.module_color = module_color
138138
if func_name_color:
139-
if type(func_name_color) is not tuple:
139+
if not isinstance(func_name_color, tuple):
140140
raise TypeError('`func_name_color` must be a tuple!')
141141
self.func_name_color = func_name_color
142142
if thread_name_color:
143-
if type(thread_name_color) is not tuple:
143+
if not isinstance(thread_name_color, tuple):
144144
raise TypeError('`thread_name_color` must be a tuple!')
145145
self.thread_name_color = thread_name_color
146146
if message_color:
147-
if type(message_color) is not tuple:
147+
if not isinstance(message_color, tuple):
148148
raise TypeError('`message_color` must be a tuple!')
149149
self.message_color = message_color
150150

log21/PPrint.py

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

10-
from typing import Dict as _Dict, Union as _Union
10+
from typing import Mapping as _Mapping, Union as _Union
1111
from pprint import PrettyPrinter as _PrettyPrinter
1212

1313
from log21.Colors import get_colors as _gc
@@ -65,7 +65,7 @@ def __lt__(self, other):
6565

6666

6767
class PrettyPrinter(_PrettyPrinter):
68-
signs_colors: _Dict[str, str] = {
68+
signs_colors: _Mapping[str, str] = {
6969
'square-brackets': _gc('LightCyan'),
7070
'curly-braces': _gc('LightBlue'),
7171
'parenthesis': _gc('LightGreen'),
@@ -75,7 +75,7 @@ class PrettyPrinter(_PrettyPrinter):
7575
'data': _gc('Green')
7676
}
7777

78-
def __init__(self, indent=1, width=80, depth=None, stream=None, signs_colors: _Dict[str, str] = None, *,
78+
def __init__(self, indent=1, width=80, depth=None, stream=None, signs_colors: _Mapping[str, str] = None, *,
7979
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
@@ -562,7 +562,7 @@ 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: _Dict[str, str] = None, *, compact=False,
565+
def pformat(obj, indent=1, width=80, depth=None, signs_colors: _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,

log21/ProgressBar.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33

44
import shutil as _shutil
55

6-
from typing import Dict as _Dict, Any as _Any
6+
from typing import Mapping as _Mapping, Any as _Any
77

88
import log21 as _log21
99
from log21.Logger import Logger as _Logger
@@ -42,7 +42,7 @@ class ProgressBar:
4242
def __init__(self, *args, width: int = None, show_percentage: bool = True, prefix: str = '|', suffix: str = '|',
4343
fill: str = '█', empty: str = ' ', format_: str = None, style: str = '%',
4444
new_line_when_complete: bool = True, colors: dict = None, no_color: bool = False,
45-
logger: '_log21.Logger' = _logger, additional_variables: _Dict[str, _Any] = None):
45+
logger: '_log21.Logger' = _logger, additional_variables: _Mapping[str, _Any] = None):
4646
"""
4747
:param args: Prevents the use of positional arguments
4848
:param width: The width of the progress bar
@@ -87,8 +87,8 @@ def __init__(self, *args, width: int = None, show_percentage: bool = True, prefi
8787
if colors and no_color:
8888
raise PermissionError('You cannot use `no_color` and `colors` parameters together!')
8989
if additional_variables:
90-
if not isinstance(additional_variables, dict):
91-
raise TypeError('`additional_variables` must be a dictionary')
90+
if not isinstance(additional_variables, _Mapping):
91+
raise TypeError('`additional_variables` must be a dictionary like object.')
9292
for key, value in additional_variables.items():
9393
if not isinstance(key, str):
9494
raise TypeError('`additional_variables` keys must be strings')

log21/TreePrint.py

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

4-
from typing import Union as _Union
4+
from typing import Union as _Union, Mapping as _Mapping, Sequence as _Sequence
55

66
from log21.Colors import get_colors as _gc
77

@@ -13,8 +13,8 @@ class Node:
1313
'fruit': _gc('LightMagenta'),
1414
}
1515

16-
def __init__(self, value: _Union[str, int], children: list = None, indent: int = 4, colors: dict = None,
17-
mode='-'):
16+
def __init__(self, value: _Union[str, int], children: list = None, indent: int = 4,
17+
colors: _Mapping[str, str] = None, mode='-'):
1818
self.value = str(value)
1919
if children:
2020
self._children = children
@@ -106,9 +106,9 @@ def get_child(self, value: str = None, index: int = None):
106106
return self._children[index]
107107

108108
@staticmethod
109-
def add_to(node: 'TreePrint.Node', data: _Union[dict, list, str, int], indent: int = 4, colors: dict = None,
110-
mode='-'):
111-
if isinstance(data, dict):
109+
def add_to(node: 'TreePrint.Node', data: _Union[_Mapping, _Sequence, str, int], indent: int = 4,
110+
colors: _Mapping[str, str] = None, mode='-'):
111+
if isinstance(data, _Mapping):
112112
if len(data) == 1:
113113
child = TreePrint.Node(list(data.keys())[0], indent=indent, colors=colors, mode=mode)
114114
TreePrint.Node.add_to(child, list(data.values())[0], indent=indent, colors=colors, mode=mode)
@@ -118,14 +118,14 @@ def add_to(node: 'TreePrint.Node', data: _Union[dict, list, str, int], indent: i
118118
child = TreePrint.Node(key, indent=indent, colors=colors, mode=mode)
119119
TreePrint.Node.add_to(child, value, indent=indent, colors=colors, mode=mode)
120120
node.add_child(child)
121-
elif isinstance(data, list):
121+
elif isinstance(data, _Sequence):
122122
for value in data:
123-
if isinstance(value, dict):
123+
if isinstance(value, _Mapping):
124124
for key, dict_value in value.items():
125125
child = TreePrint.Node(key, indent=indent, colors=colors, mode=mode)
126126
TreePrint.Node.add_to(child, dict_value, indent=indent, colors=colors, mode=mode)
127127
node.add_child(child)
128-
elif isinstance(value, list):
128+
elif isinstance(value, _Sequence):
129129
child = TreePrint.Node('>', indent=indent, colors=colors, mode=mode)
130130
TreePrint.Node.add_to(child, value, indent=indent, colors=colors, mode=mode)
131131
node.add_child(child)
@@ -136,23 +136,24 @@ def add_to(node: 'TreePrint.Node', data: _Union[dict, list, str, int], indent: i
136136
child = TreePrint.Node(str(data), indent=indent, colors=colors, mode=mode)
137137
node.add_child(child)
138138

139-
def __init__(self, data: _Union[dict, list, str, int], indent: int = 4, colors: dict = None, mode='-'):
139+
def __init__(self, data: _Union[_Mapping, _Sequence, str, int], indent: int = 4,
140+
colors: _Mapping[str, str] = None, mode='-'):
140141
self.indent = indent
141142
self.mode = mode
142-
if isinstance(data, dict):
143+
if isinstance(data, _Mapping):
143144
if len(data) == 1:
144145
self.root = self.Node(list(data.keys())[0], indent=indent, colors=colors)
145146
self.add_to_root(list(data.values()), colors=colors)
146147
else:
147148
self.root = self.Node('root', indent=indent, colors=colors)
148149
self.add_to_root(data, colors=colors)
149-
elif isinstance(data, list):
150+
elif isinstance(data, _Sequence):
150151
self.root = self.Node('root', indent=indent, colors=colors)
151152
self.add_to_root(data, colors=colors)
152153
else:
153154
self.root = self.Node(str(data), indent=indent, colors=colors)
154155

155-
def add_to_root(self, data: _Union[dict, list, str, int], colors: dict = None):
156+
def add_to_root(self, data: _Union[_Mapping, _Sequence, str, int], colors: _Mapping[str, str] = None):
156157
self.Node.add_to(self.root, data, indent=self.indent, colors=colors, mode=self.mode)
157158

158159
def __str__(self, mode=None):
@@ -161,5 +162,6 @@ def __str__(self, mode=None):
161162
return self.root.__str__(mode=mode)
162163

163164

164-
def tree_format(data: _Union[dict, list, str, int], indent: int = 4, mode='-', colors: dict = None):
165+
def tree_format(data: _Union[_Mapping, _Sequence, str, int], indent: int = 4, mode='-',
166+
colors: _Mapping[str, str] = None):
165167
return str(TreePrint(data, indent=indent, colors=colors, mode=mode))

0 commit comments

Comments
 (0)