diff --git a/loguru/_colorizer.py b/loguru/_colorizer.py index ed87cdb27..18c072bd6 100644 --- a/loguru/_colorizer.py +++ b/loguru/_colorizer.py @@ -238,10 +238,9 @@ def feed(self, text, *, raw=False): self._tokens.append((TokenType.CLOSING, "\033[0m")) self._tokens.extend(self._color_tokens) continue - elif tag in self._tags: + if tag in self._tags: raise ValueError('Closing tag "%s" violates nesting rules' % markup) - else: - raise ValueError('Closing tag "%s" has no corresponding opening tag' % markup) + raise ValueError('Closing tag "%s" has no corresponding opening tag' % markup) if tag in {"lvl", "level"}: token = (TokenType.LEVEL, None) @@ -280,29 +279,29 @@ def _get_ansicode(self, tag): # Substitute on a direct match. if tag in style: return style[tag] - elif tag in foreground: + if tag in foreground: return foreground[tag] - elif tag in background: + if tag in background: return background[tag] # An alternative syntax for setting the color (e.g. , ). - elif tag.startswith("fg ") or tag.startswith("bg "): + if tag.startswith("fg ") or tag.startswith("bg "): st, color = tag[:2], tag[3:] code = "38" if st == "fg" else "48" if st == "fg" and color.lower() in foreground: return foreground[color.lower()] - elif st == "bg" and color.upper() in background: + if st == "bg" and color.upper() in background: return background[color.upper()] - elif color.isdigit() and int(color) <= 255: + if color.isdigit() and int(color) <= 255: return "\033[%s;5;%sm" % (code, color) - elif re.match(r"#(?:[a-fA-F0-9]{3}){1,2}$", color): + if re.match(r"#(?:[a-fA-F0-9]{3}){1,2}$", color): hex_color = color[1:] if len(hex_color) == 3: hex_color *= 2 rgb = tuple(int(hex_color[i : i + 2], 16) for i in (0, 2, 4)) return "\033[%s;2;%s;%s;%sm" % ((code,) + rgb) - elif color.count(",") == 2: + if color.count(",") == 2: colors = tuple(color.split(",")) if all(x.isdigit() and int(x) <= 255 for x in colors): return "\033[%s;2;%s;%s;%sm" % ((code,) + colors) diff --git a/loguru/_ctime_functions.py b/loguru/_ctime_functions.py index e232b4276..a5e345a8b 100644 --- a/loguru/_ctime_functions.py +++ b/loguru/_ctime_functions.py @@ -19,7 +19,7 @@ def set_ctime_windows(filepath, timestamp): return get_ctime_windows, set_ctime_windows - elif hasattr(os.stat_result, "st_birthtime"): + if hasattr(os.stat_result, "st_birthtime"): def get_ctime_macos(filepath): return os.stat(filepath).st_birthtime @@ -29,7 +29,7 @@ def set_ctime_macos(filepath, timestamp): return get_ctime_macos, set_ctime_macos - elif hasattr(os, "getxattr") and hasattr(os, "setxattr"): + if hasattr(os, "getxattr") and hasattr(os, "setxattr"): def get_ctime_linux(filepath): try: diff --git a/loguru/_defaults.py b/loguru/_defaults.py index d3d8de76f..5456e81c7 100644 --- a/loguru/_defaults.py +++ b/loguru/_defaults.py @@ -9,7 +9,7 @@ def env(key, type_, default=None): if type_ == str: return val - elif type_ == bool: + if type_ == bool: if val.lower() in ["1", "true", "yes", "y", "ok", "on"]: return True if val.lower() in ["0", "false", "no", "n", "nok", "off"]: @@ -17,13 +17,14 @@ def env(key, type_, default=None): raise ValueError( "Invalid environment variable '%s' (expected a boolean): '%s'" % (key, val) ) - elif type_ == int: + if type_ == int: try: return int(val) except ValueError: raise ValueError( "Invalid environment variable '%s' (expected an integer): '%s'" % (key, val) ) from None + raise ValueError("The requested type '%r' is not supported" % type_) LOGURU_AUTOINIT = env("LOGURU_AUTOINIT", bool, True) diff --git a/loguru/_file_sink.py b/loguru/_file_sink.py index bdc6ccd4c..4b09b06bb 100644 --- a/loguru/_file_sink.py +++ b/loguru/_file_sink.py @@ -310,7 +310,7 @@ def _make_glob_patterns(path): def _make_rotation_function(rotation): if rotation is None: return None - elif isinstance(rotation, str): + if isinstance(rotation, str): size = string_parsers.parse_size(rotation) if size is not None: return FileSink._make_rotation_function(size) @@ -330,45 +330,41 @@ def _make_rotation_function(rotation): step_forward = partial(Rotation.forward_weekday, weekday=day) return Rotation.RotationTime(step_forward, time) raise ValueError("Cannot parse rotation from: '%s'" % rotation) - elif isinstance(rotation, (numbers.Real, decimal.Decimal)): + if isinstance(rotation, (numbers.Real, decimal.Decimal)): return partial(Rotation.rotation_size, size_limit=rotation) - elif isinstance(rotation, datetime.time): + if isinstance(rotation, datetime.time): return Rotation.RotationTime(Rotation.forward_day, rotation) - elif isinstance(rotation, datetime.timedelta): + if isinstance(rotation, datetime.timedelta): step_forward = partial(Rotation.forward_interval, interval=rotation) return Rotation.RotationTime(step_forward) - elif callable(rotation): + if callable(rotation): return rotation - else: - raise TypeError( - "Cannot infer rotation for objects of type: '%s'" % type(rotation).__name__ - ) + raise TypeError("Cannot infer rotation for objects of type: '%s'" % type(rotation).__name__) @staticmethod def _make_retention_function(retention): if retention is None: return None - elif isinstance(retention, str): + if isinstance(retention, str): interval = string_parsers.parse_duration(retention) if interval is None: raise ValueError("Cannot parse retention from: '%s'" % retention) return FileSink._make_retention_function(interval) - elif isinstance(retention, int): + if isinstance(retention, int): return partial(Retention.retention_count, number=retention) - elif isinstance(retention, datetime.timedelta): + if isinstance(retention, datetime.timedelta): return partial(Retention.retention_age, seconds=retention.total_seconds()) - elif callable(retention): + if callable(retention): return retention - else: - raise TypeError( - "Cannot infer retention for objects of type: '%s'" % type(retention).__name__ - ) + raise TypeError( + "Cannot infer retention for objects of type: '%s'" % type(retention).__name__ + ) @staticmethod def _make_compression_function(compression): if compression is None: return None - elif isinstance(compression, str): + if isinstance(compression, str): ext = compression.strip().lstrip(".") if ext == "gz": @@ -426,9 +422,8 @@ def _make_compression_function(compression): raise ValueError("Invalid compression format: '%s'" % ext) return partial(Compression.compression, ext="." + ext, compress_function=compress) - elif callable(compression): + if callable(compression): return compression - else: - raise TypeError( - "Cannot infer compression for objects of type: '%s'" % type(compression).__name__ - ) + raise TypeError( + "Cannot infer compression for objects of type: '%s'" % type(compression).__name__ + ) diff --git a/loguru/_logger.py b/loguru/_logger.py index f750967a5..ec9d28494 100644 --- a/loguru/_logger.py +++ b/loguru/_logger.py @@ -1225,7 +1225,7 @@ def __enter__(self): def __exit__(self, type_, value, traceback_): if type_ is None: - return + return None if not issubclass(type_, exception): return False @@ -1582,8 +1582,7 @@ def level(self, name, no=None, color=None, icon=None): "Level '%s' does not exist, you have to create it by specifying a level no" % name ) - else: - old_color, old_icon = "", " " + old_color, old_icon = "", " " elif no is not None: raise TypeError("Level '%s' already exists, you can't update its severity no" % name) else: diff --git a/loguru/_string_parsers.py b/loguru/_string_parsers.py index 1e135ab21..4fa67c151 100644 --- a/loguru/_string_parsers.py +++ b/loguru/_string_parsers.py @@ -51,9 +51,7 @@ def parse_size(size): u = "kmgtpezy".index(u.lower()) + 1 if u else 0 i = 1024 if i else 1000 b = {"b": 8, "B": 1}[b] if b else 1 - size = s * i**u / b - - return size + return s * i**u / b def parse_duration(duration): @@ -118,7 +116,7 @@ def parse_day(day): day = day.strip().lower() if day in days: return days[day] - elif day.startswith("w") and day[1:].isdigit(): + if day.startswith("w") and day[1:].isdigit(): day = int(day[1:]) if not 0 <= day < 7: raise ValueError("Invalid weekday value while parsing day (expected [0-6]): '%d'" % day) diff --git a/pyproject.toml b/pyproject.toml index 94ddbb911..87cbb24f8 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -18,7 +18,7 @@ testpaths = ["tests"] exclude = ["tests/exceptions/source/*"] line-length = 100 # Enforce pyflakes(F), pycodestyle(E, W), isort (I), bugbears (B), and pep8-naming (N) rules. -select = ["F", "E", "W", "I", "B", "N"] +select = ["F", "E", "W", "I", "B", "N", "RET"] [tool.ruff.pycodestyle] max-doc-length = 100 diff --git a/tests/conftest.py b/tests/conftest.py index ff0191b79..60442bbaf 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -54,8 +54,7 @@ def parse(text, *, strip=False, strict=True): if strip: return parser.strip(tokens) - else: - return parser.colorize(tokens, "") + return parser.colorize(tokens, "") def check_dir(dir, *, files=None, size=None): diff --git a/tests/test_add_option_catch.py b/tests/test_add_option_catch.py index 9551f7065..5bf1b41f6 100644 --- a/tests/test_add_option_catch.py +++ b/tests/test_add_option_catch.py @@ -115,8 +115,7 @@ def half_broken_sink(m): nonlocal output if m.startswith("NOK"): raise ValueError("Broken!") - else: - output += m + output += m logger.add(half_broken_sink, format="{message}", enqueue=enqueue, catch=True) logger.info("A") diff --git a/tests/test_defaults.py b/tests/test_defaults.py index c8d039c6d..148ffe249 100644 --- a/tests/test_defaults.py +++ b/tests/test_defaults.py @@ -50,3 +50,11 @@ def test_invalid_bool(value, monkeypatch): context.setenv(key, value) with pytest.raises(ValueError): env(key, bool) + + +def test_invalid_type(monkeypatch): + with monkeypatch.context() as context: + key = "INVALID_TYPE" + context.setenv(key, 42.0) + with pytest.raises(ValueError): + env(key, float)