Skip to content

Commit

Permalink
Minor style / performance fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
hynek committed Apr 6, 2023
1 parent 776864b commit db7a294
Show file tree
Hide file tree
Showing 12 changed files with 54 additions and 60 deletions.
3 changes: 2 additions & 1 deletion src/structlog/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,8 @@ def __getattr__(name: str) -> str:

if name == "__uri__":
return meta["Project-URL"].split(" ", 1)[-1]
elif name == "__email__":

if name == "__email__":
return meta["Author-email"].split("<", 1)[1].rstrip(">")

return meta[dunder_to_metadata[name]]
25 changes: 12 additions & 13 deletions src/structlog/_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,10 +57,7 @@ def __repr__(self) -> str:

def __eq__(self, other: Any) -> bool:
try:
if self._context == other._context:
return True
else:
return False
return self._context == other._context
except AttributeError:
return False

Expand Down Expand Up @@ -163,18 +160,20 @@ def _process_event(

if isinstance(event_dict, (str, bytes, bytearray)):
return (event_dict,), {}
elif isinstance(event_dict, tuple):

if isinstance(event_dict, tuple):
# In this case we assume that the last processor returned a tuple
# of ``(args, kwargs)`` and pass it right through.
return event_dict # type: ignore[return-value]
elif isinstance(event_dict, dict):

if isinstance(event_dict, dict):
return (), event_dict
else:
raise ValueError(
"Last processor didn't return an appropriate value. Valid "
"return values are a dict, a tuple of (args, kwargs), bytes, "
"or a str."
)

raise ValueError(
"Last processor didn't return an appropriate value. Valid "
"return values are a dict, a tuple of (args, kwargs), bytes, "
"or a str."
)

def _proxy_to_logger(
self, method_name: str, event: str | None = None, **event_kw: Any
Expand Down Expand Up @@ -205,7 +204,7 @@ def _proxy_to_logger(
args, kw = self._process_event(method_name, event, event_kw)
return getattr(self._logger, method_name)(*args, **kw)
except DropEvent:
return
return None


def get_context(bound_logger: BindableLogger) -> Context:
Expand Down
12 changes: 6 additions & 6 deletions src/structlog/_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -255,7 +255,9 @@ def configure_once(
cache_logger_on_first_use=cache_logger_on_first_use,
)
else:
warnings.warn("Repeated configuration attempted.", RuntimeWarning)
warnings.warn(
"Repeated configuration attempted.", RuntimeWarning, stacklevel=2
)


def reset_defaults() -> None:
Expand Down Expand Up @@ -346,8 +348,8 @@ def finalized_bind(**new_values: Any) -> BindableLogger:
"""
if new_values:
return logger.bind(**new_values)
else:
return logger

return logger

if self._cache_logger_on_first_use is True or (
self._cache_logger_on_first_use is None
Expand Down Expand Up @@ -377,9 +379,7 @@ def new(self, **new_values: Any) -> BindableLogger:
else:
_CONFIG.default_context_class().clear()

bl = self.bind(**new_values)

return bl
return self.bind(**new_values)

def __getattr__(self, name: str) -> Any:
"""
Expand Down
6 changes: 3 additions & 3 deletions src/structlog/_output.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ def __getstate__(self) -> str:
if self._file is stdout:
return "stdout"

elif self._file is stderr:
if self._file is stderr:
return "stderr"

raise PicklingError(
Expand Down Expand Up @@ -171,7 +171,7 @@ def __getstate__(self) -> str:
if self._file is stdout:
return "stdout"

elif self._file is stderr:
if self._file is stderr:
return "stderr"

raise PicklingError(
Expand Down Expand Up @@ -271,7 +271,7 @@ def __getstate__(self) -> str:
if self._file is sys.stdout.buffer:
return "stdout"

elif self._file is sys.stderr.buffer:
if self._file is sys.stderr.buffer:
return "stderr"

raise PicklingError(
Expand Down
6 changes: 3 additions & 3 deletions src/structlog/_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
import errno
import sys

from contextlib import suppress
from typing import Any, Callable


Expand Down Expand Up @@ -41,8 +42,7 @@ def get_processname() -> str:
# Errors may occur if multiprocessing has not finished loading
# yet - e.g. if a custom import hook causes third-party code
# to run when multiprocessing calls import.
try:
with suppress(Exception):
processname = mp.current_process().name
except Exception:
pass

return processname
14 changes: 6 additions & 8 deletions src/structlog/dev.py
Original file line number Diff line number Diff line change
Expand Up @@ -321,7 +321,7 @@ def __init__(
else:
self._level_to_color = level_styles

for key in self._level_to_color.keys():
for key in self._level_to_color:
self._level_to_color[key] += styles.bright
self._longest_level = len(
max(self._level_to_color.keys(), key=lambda e: len(e))
Expand All @@ -342,8 +342,8 @@ def _repr(self, val: Any) -> str:

if isinstance(val, str):
return val
else:
return repr(val)

return repr(val)

def __call__(
self, logger: WrappedLogger, name: str, event_dict: EventDict
Expand Down Expand Up @@ -428,7 +428,8 @@ def __call__(
if self._exception_formatter is not plain_traceback:
warnings.warn(
"Remove `format_exc_info` from your processor chain "
"if you want pretty exceptions."
"if you want pretty exceptions.",
stacklevel=2,
)
sio.write("\n" + exc)

Expand All @@ -451,10 +452,7 @@ def get_default_level_styles(colors: bool = True) -> Any:
*colors* parameter to `ConsoleRenderer`. Default: `True`.
"""
styles: Styles
if colors:
styles = _ColorfulStyles
else:
styles = _PlainStyles
styles = _ColorfulStyles if colors else _PlainStyles
return {
"critical": styles.level_critical,
"exception": styles.level_exception,
Expand Down
23 changes: 13 additions & 10 deletions src/structlog/processors.py
Original file line number Diff line number Diff line change
Expand Up @@ -95,8 +95,8 @@ def __init__(
def _repr(inst: Any) -> str:
if isinstance(inst, str):
return inst
else:
return repr(inst)

return repr(inst)

self._repr = _repr

Expand Down Expand Up @@ -336,11 +336,11 @@ def _json_fallback_handler(obj: Any) -> Any:

if isinstance(obj, _ThreadLocalDictWrapper):
return obj._dict
else:
try:
return obj.__structlog__()
except AttributeError:
return repr(obj)

try:
return obj.__structlog__()
except AttributeError:
return repr(obj)


class ExceptionRenderer:
Expand Down Expand Up @@ -492,7 +492,8 @@ def stamper_unix(event_dict: EventDict) -> EventDict:
return event_dict

return stamper_unix
elif fmt.upper() == "ISO":

if fmt.upper() == "ISO":

def stamper_iso_local(event_dict: EventDict) -> EventDict:
event_dict[key] = now().isoformat()
Expand Down Expand Up @@ -522,9 +523,11 @@ def _figure_out_exc_info(v: Any) -> ExcInfo:
"""
if isinstance(v, BaseException):
return (v.__class__, v, v.__traceback__)
elif isinstance(v, tuple):

if isinstance(v, tuple):
return v # type: ignore[return-value]
elif v:

if v:
return sys.exc_info() # type: ignore[return-value]

return v
Expand Down
7 changes: 2 additions & 5 deletions src/structlog/stdlib.py
Original file line number Diff line number Diff line change
Expand Up @@ -114,10 +114,7 @@ def findCaller(
"""
sinfo: str | None
f, name = _find_first_app_frame_and_name(["logging"])
if stack_info:
sinfo = _format_stack(f)
else:
sinfo = None
sinfo = _format_stack(f) if stack_info else None

return f.f_code.co_filename, f.f_lineno, f.f_code.co_name, sinfo

Expand Down Expand Up @@ -788,7 +785,7 @@ def add_logger_name(


_LOG_RECORD_KEYS = logging.LogRecord(
"name", 0, "pathname", 0, "msg", tuple(), None
"name", 0, "pathname", 0, "msg", (), None
).__dict__.keys()


Expand Down
4 changes: 2 additions & 2 deletions src/structlog/testing.py
Original file line number Diff line number Diff line change
Expand Up @@ -108,8 +108,8 @@ def msg(self, *args: Any, **kw: Any) -> Any:
# Slightly convoluted for backwards compatibility.
if len(args) == 1 and not kw:
return args[0]
else:
return args, kw

return args, kw

log = debug = info = warn = warning = msg
fatal = failure = err = error = critical = exception = msg
Expand Down
4 changes: 1 addition & 3 deletions src/structlog/threadlocal.py
Original file line number Diff line number Diff line change
Expand Up @@ -216,9 +216,7 @@ def __len__(self) -> int:
return self._dict.__len__()

def __getattr__(self, name: str) -> Any:
method = getattr(self._dict, name)

return method
return getattr(self._dict, name)


_CONTEXT = threading.local()
Expand Down
6 changes: 2 additions & 4 deletions src/structlog/tracebacks.py
Original file line number Diff line number Diff line change
Expand Up @@ -202,8 +202,7 @@ def extract(
# No cover, code is reached but coverage doesn't recognize it.
break # pragma: no cover

trace = Trace(stacks=stacks)
return trace
return Trace(stacks=stacks)


class ExceptionDictTransformer:
Expand Down Expand Up @@ -266,5 +265,4 @@ def __call__(self, exc_info: ExcInfo) -> list[dict[str, Any]]:
*stack.frames[-half:],
]

stack_dicts = [asdict(stack) for stack in trace.stacks]
return stack_dicts
return [asdict(stack) for stack in trace.stacks]
4 changes: 2 additions & 2 deletions src/structlog/twisted.py
Original file line number Diff line number Diff line change
Expand Up @@ -324,5 +324,5 @@ def __call__(
"_why": self._dictRenderer(logger, name, eventDict),
},
)
else:
return self._dictRenderer(logger, name, eventDict)

return self._dictRenderer(logger, name, eventDict)

0 comments on commit db7a294

Please sign in to comment.