Skip to content

Commit 30e63e8

Browse files
Update loguru
1 parent f25103c commit 30e63e8

14 files changed

+174
-103
lines changed

loguru/__init__.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
44
Just ``from loguru import logger``.
55
"""
6+
67
import atexit as _atexit
78
import sys as _sys
89

loguru/__init__.pyi

Lines changed: 22 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -87,6 +87,7 @@ It helps to catch several possible runtime errors by performing additional check
8787
For more details, go to official |documentation of loguru-mypy|_.
8888
"""
8989

90+
import sys
9091
from asyncio import AbstractEventLoop
9192
from datetime import datetime, time, timedelta
9293
from picologging import Handler
@@ -113,9 +114,25 @@ from typing import (
113114
overload,
114115
)
115116

116-
from typing import Awaitable, Protocol, TypedDict, ContextManager
117-
from os import PathLike
118-
PathLikeStr = PathLike[str]
117+
if sys.version_info >= (3, 5, 3):
118+
from typing import Awaitable
119+
else:
120+
from typing_extensions import Awaitable
121+
122+
if sys.version_info >= (3, 6):
123+
from os import PathLike
124+
from typing import ContextManager
125+
126+
PathLikeStr = PathLike[str]
127+
else:
128+
from pathlib import PurePath as PathLikeStr
129+
130+
from typing_extensions import ContextManager
131+
132+
if sys.version_info >= (3, 8):
133+
from typing import Protocol, TypedDict
134+
else:
135+
from typing_extensions import Protocol, TypedDict
119136

120137
_T = TypeVar("_T")
121138
_F = TypeVar("_F", bound=Callable[..., Any])
@@ -278,7 +295,7 @@ class Logger:
278295
def remove(self, handler_id: Optional[int] = ...) -> None: ...
279296
def complete(self) -> AwaitableCompleter: ...
280297
@overload
281-
def catch( # type: ignore[misc]
298+
def catch(
282299
self,
283300
exception: Union[Type[BaseException], Tuple[Type[BaseException], ...]] = ...,
284301
*,
@@ -290,7 +307,7 @@ class Logger:
290307
message: str = ...
291308
) -> Catcher: ...
292309
@overload
293-
def catch(self, exception: _F) -> _F: ...
310+
def catch(self, function: _F) -> _F: ...
294311
def opt(
295312
self,
296313
*,

loguru/_asyncio_loop.py

Lines changed: 18 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,26 @@
11
import asyncio
2+
import sys
23

34

45
def load_loop_functions():
5-
def get_task_loop(task):
6-
return task.get_loop()
6+
if sys.version_info >= (3, 7):
7+
8+
def get_task_loop(task):
9+
return task.get_loop()
10+
11+
get_running_loop = asyncio.get_running_loop
12+
13+
else:
14+
15+
def get_task_loop(task):
16+
return task._loop
17+
18+
def get_running_loop():
19+
loop = asyncio.get_event_loop()
20+
if not loop.is_running():
21+
raise RuntimeError("There is no running event loop")
22+
return loop
723

8-
get_running_loop = asyncio.get_running_loop
924
return get_task_loop, get_running_loop
1025

1126

loguru/_better_exceptions.py

Lines changed: 51 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -10,9 +10,23 @@
1010
import tokenize
1111
import traceback
1212

13+
if sys.version_info >= (3, 11):
1314

14-
def is_exception_group(exc):
15-
return isinstance(exc, ExceptionGroup)
15+
def is_exception_group(exc):
16+
return isinstance(exc, ExceptionGroup)
17+
18+
else:
19+
try:
20+
from exceptiongroup import ExceptionGroup
21+
except ImportError:
22+
23+
def is_exception_group(exc):
24+
return False
25+
26+
else:
27+
28+
def is_exception_group(exc):
29+
return isinstance(exc, ExceptionGroup)
1630

1731

1832
class SyntaxHighlighter:
@@ -31,7 +45,7 @@ class SyntaxHighlighter:
3145

3246
_builtins = set(dir(builtins))
3347
_constants = {"True", "False", "None"}
34-
_punctation = {"(", ")", "[", "]", "{", "}", ":", ",", ";"}
48+
_punctuation = {"(", ")", "[", "]", "{", "}", ":", ",", ";"}
3549
_strings = {tokenize.STRING}
3650
_fstring_middle = None
3751

@@ -65,7 +79,7 @@ def highlight(self, source):
6579
else:
6680
color = style["identifier"]
6781
elif type_ == tokenize.OP:
68-
if string in self._punctation:
82+
if string in self._punctuation:
6983
color = style["punctuation"]
7084
else:
7185
color = style["operator"]
@@ -441,31 +455,31 @@ def _format_exception(
441455
# on the indentation; the preliminary context for "SyntaxError" is always indented, while
442456
# the Exception itself is not. This allows us to identify the correct index for the
443457
# exception message.
444-
error_message_index = 0
445-
for error_message_index, part in enumerate(exception_only): # noqa: B007
446-
if not part.startswith(" "):
447-
break
448-
449-
error_message = exception_only[error_message_index][:-1] # Remove last new line temporarily
450-
451-
if self._colorize:
452-
if ":" in error_message:
453-
exception_type, exception_value = error_message.split(":", 1)
454-
exception_type = self._theme["exception_type"].format(exception_type)
455-
exception_value = self._theme["exception_value"].format(exception_value)
456-
error_message = exception_type + ":" + exception_value
457-
else:
458-
error_message = self._theme["exception_type"].format(error_message)
458+
no_indented_indexes = (i for i, p in enumerate(exception_only) if not p.startswith(" "))
459+
error_message_index = next(no_indented_indexes, None)
459460

460-
if self._diagnose and frames:
461-
if issubclass(exc_type, AssertionError) and not str(exc_value) and final_source:
462-
if self._colorize:
463-
final_source = self._syntax_highlighter.highlight(final_source)
464-
error_message += ": " + final_source
461+
if error_message_index is not None:
462+
# Remove final new line temporarily.
463+
error_message = exception_only[error_message_index][:-1]
464+
465+
if self._colorize:
466+
if ":" in error_message:
467+
exception_type, exception_value = error_message.split(":", 1)
468+
exception_type = self._theme["exception_type"].format(exception_type)
469+
exception_value = self._theme["exception_value"].format(exception_value)
470+
error_message = exception_type + ":" + exception_value
471+
else:
472+
error_message = self._theme["exception_type"].format(error_message)
473+
474+
if self._diagnose and frames:
475+
if issubclass(exc_type, AssertionError) and not str(exc_value) and final_source:
476+
if self._colorize:
477+
final_source = self._syntax_highlighter.highlight(final_source)
478+
error_message += ": " + final_source
465479

466-
error_message = "\n" + error_message
480+
error_message = "\n" + error_message
467481

468-
exception_only[error_message_index] = error_message + "\n"
482+
exception_only[error_message_index] = error_message + "\n"
469483

470484
if is_first:
471485
yield self._prefix
@@ -484,7 +498,7 @@ def _format_exception(
484498
else:
485499
yield from self._indent(introduction + "\n", group_nesting)
486500

487-
frames_lines = traceback.format_list(frames) + exception_only
501+
frames_lines = self._format_list(frames) + exception_only
488502
if self._colorize or self._backtrace or self._diagnose:
489503
frames_lines = self._format_locations(frames_lines, has_introduction=has_introduction)
490504

@@ -512,5 +526,15 @@ def _format_exception(
512526
if not is_exception_group(exc) or group_nesting == 10:
513527
yield from self._indent("-" * 35, group_nesting + 1, prefix="+-")
514528

529+
def _format_list(self, frames):
530+
result = []
531+
for filename, lineno, name, line in frames:
532+
row = []
533+
row.append(' File "{}", line {}, in {}\n'.format(filename, lineno, name))
534+
if line:
535+
row.append(" {}\n".format(line.strip()))
536+
result.append("".join(row))
537+
return result
538+
515539
def format_exception(self, type_, value, tb, *, from_decorator=False):
516540
yield from self._format_exception(value, tb, is_first=True, from_decorator=from_decorator)

loguru/_colorama.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import builtins
12
import os
23
import sys
34

@@ -6,7 +7,7 @@ def should_colorize(stream):
67
if stream is None:
78
return False
89

9-
if stream is sys.stdout or stream is sys.stderr:
10+
if getattr(builtins, "__IPYTHON__", False) and (stream is sys.stdout or stream is sys.stderr):
1011
try:
1112
import ipykernel
1213
import IPython

loguru/_colorizer.py

Lines changed: 15 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -238,10 +238,9 @@ def feed(self, text, *, raw=False):
238238
self._tokens.append((TokenType.CLOSING, "\033[0m"))
239239
self._tokens.extend(self._color_tokens)
240240
continue
241-
elif tag in self._tags:
241+
if tag in self._tags:
242242
raise ValueError('Closing tag "%s" violates nesting rules' % markup)
243-
else:
244-
raise ValueError('Closing tag "%s" has no corresponding opening tag' % markup)
243+
raise ValueError('Closing tag "%s" has no corresponding opening tag' % markup)
245244

246245
if tag in {"lvl", "level"}:
247246
token = (TokenType.LEVEL, None)
@@ -280,29 +279,29 @@ def _get_ansicode(self, tag):
280279
# Substitute on a direct match.
281280
if tag in style:
282281
return style[tag]
283-
elif tag in foreground:
282+
if tag in foreground:
284283
return foreground[tag]
285-
elif tag in background:
284+
if tag in background:
286285
return background[tag]
287286

288287
# An alternative syntax for setting the color (e.g. <fg red>, <bg red>).
289-
elif tag.startswith("fg ") or tag.startswith("bg "):
288+
if tag.startswith("fg ") or tag.startswith("bg "):
290289
st, color = tag[:2], tag[3:]
291290
code = "38" if st == "fg" else "48"
292291

293292
if st == "fg" and color.lower() in foreground:
294293
return foreground[color.lower()]
295-
elif st == "bg" and color.upper() in background:
294+
if st == "bg" and color.upper() in background:
296295
return background[color.upper()]
297-
elif color.isdigit() and int(color) <= 255:
296+
if color.isdigit() and int(color) <= 255:
298297
return "\033[%s;5;%sm" % (code, color)
299-
elif re.match(r"#(?:[a-fA-F0-9]{3}){1,2}$", color):
298+
if re.match(r"#(?:[a-fA-F0-9]{3}){1,2}$", color):
300299
hex_color = color[1:]
301300
if len(hex_color) == 3:
302301
hex_color *= 2
303302
rgb = tuple(int(hex_color[i : i + 2], 16) for i in (0, 2, 4))
304303
return "\033[%s;2;%s;%s;%sm" % ((code,) + rgb)
305-
elif color.count(",") == 2:
304+
if color.count(",") == 2:
306305
colors = tuple(color.split(","))
307306
if all(x.isdigit() and int(x) <= 255 for x in colors):
308307
return "\033[%s;2;%s;%s;%sm" % ((code,) + colors)
@@ -339,10 +338,12 @@ def colorize(self, ansi_level):
339338

340339
def make_coloring_message(self, message, *, ansi_level, colored_message):
341340
messages = [
342-
message
343-
if color_tokens is None
344-
else AnsiParser.wrap(
345-
colored_message.tokens, ansi_level=ansi_level, color_tokens=color_tokens
341+
(
342+
message
343+
if color_tokens is None
344+
else AnsiParser.wrap(
345+
colored_message.tokens, ansi_level=ansi_level, color_tokens=color_tokens
346+
)
346347
)
347348
for color_tokens in self._messages_color_tokens
348349
]

loguru/_contextvars.py

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,14 @@
1+
import sys
2+
3+
14
def load_contextvar_class():
2-
from contextvars import ContextVar
5+
if sys.version_info >= (3, 7):
6+
from contextvars import ContextVar
7+
elif sys.version_info >= (3, 5, 3):
8+
from aiocontextvars import ContextVar
9+
else:
10+
from contextvars import ContextVar
11+
312
return ContextVar
413

514

loguru/_ctime_functions.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ def set_ctime_windows(filepath, timestamp):
1919

2020
return get_ctime_windows, set_ctime_windows
2121

22-
elif hasattr(os.stat_result, "st_birthtime"):
22+
if hasattr(os.stat_result, "st_birthtime"):
2323

2424
def get_ctime_macos(filepath):
2525
return os.stat(filepath).st_birthtime
@@ -29,7 +29,7 @@ def set_ctime_macos(filepath, timestamp):
2929

3030
return get_ctime_macos, set_ctime_macos
3131

32-
elif hasattr(os, "getxattr") and hasattr(os, "setxattr"):
32+
if hasattr(os, "getxattr") and hasattr(os, "setxattr"):
3333

3434
def get_ctime_linux(filepath):
3535
try:

loguru/_defaults.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,21 +9,22 @@ def env(key, type_, default=None):
99

1010
if type_ == str:
1111
return val
12-
elif type_ == bool:
12+
if type_ == bool:
1313
if val.lower() in ["1", "true", "yes", "y", "ok", "on"]:
1414
return True
1515
if val.lower() in ["0", "false", "no", "n", "nok", "off"]:
1616
return False
1717
raise ValueError(
1818
"Invalid environment variable '%s' (expected a boolean): '%s'" % (key, val)
1919
)
20-
elif type_ == int:
20+
if type_ == int:
2121
try:
2222
return int(val)
2323
except ValueError:
2424
raise ValueError(
2525
"Invalid environment variable '%s' (expected an integer): '%s'" % (key, val)
2626
) from None
27+
raise ValueError("The requested type '%r' is not supported" % type_)
2728

2829

2930
LOGURU_AUTOINIT = env("LOGURU_AUTOINIT", bool, True)

0 commit comments

Comments
 (0)