From e64b6f8e5f6c1af57cf6c5dd9ad74cb934b57c44 Mon Sep 17 00:00:00 2001 From: Wolfgang Müller Date: Tue, 27 Apr 2021 15:46:01 +0200 Subject: formatter: Use functools.partial to simplify the formatter Instead of defining a function for every message format that trivially returns an f-string, have a generic partially-applied helper function that applies the Message object as a dictionary to the format() function. That way, we can inline the formatter definitions directly in the FORMATTERS dictionary. --- quarg/quassel/formatter.py | 41 +++++++++-------------------------------- 1 file changed, 9 insertions(+), 32 deletions(-) (limited to 'quarg/quassel/formatter.py') diff --git a/quarg/quassel/formatter.py b/quarg/quassel/formatter.py index 1297288..59793fc 100644 --- a/quarg/quassel/formatter.py +++ b/quarg/quassel/formatter.py @@ -1,6 +1,6 @@ import datetime -# from functools import partial +from functools import partial from typing import NamedTuple from quarg.quassel.types import MessageType @@ -37,24 +37,6 @@ def format_from(backlog_row): return f'{timestamp}\t{message.buffer}\t{formatter(message)}' -def format_privmsg(msg): - return f'<{msg.user}> {msg.message}' - -def format_notice(msg): - return f'[{msg.user}] {msg.message}' - -def format_action(msg): - return f'-*- {msg.user} {msg.message}' - -def format_nick(msg): - return f'<-> {msg.user} is now known as {msg.message}' - -def format_mode(msg): - return f'*** Mode {msg.message} by {msg.user}' - -def format_join(msg): - return f'--> {msg.user} ({msg.user.host}) has joined {msg.buffer}' - def format_part(msg): if msg.message: return f'<-- {msg.user} has left {msg.buffer} ({msg.message})' @@ -109,21 +91,16 @@ def format_netsplit_quit(msg): have_quit = ', '.join(user.nick for user in users) return f'<= Netsplit between {srv_left} and {srv_right}. Users quit: {have_quit}' -# TODO inline the format strings here and have a wrapper function that gives msg? -# TODO also .format(**msg) - -def format_from_string(string, msg): - return string.format(**msg._asdict()) - -# MessageType.PART: partial(format_from_string, '<-- {user} has left {buffer}'), +def fmt(string): + return partial(lambda string, msg: string.format(**msg._asdict()), string) FORMATTERS = { - MessageType.PRIVMSG: format_privmsg, - MessageType.NOTICE: format_notice, - MessageType.ACTION: format_action, - MessageType.NICK: format_nick, - MessageType.MODE: format_mode, - MessageType.JOIN: format_join, + MessageType.PRIVMSG: fmt('<{user}> {message}'), + MessageType.NOTICE: fmt('[{user}] {message}'), + MessageType.ACTION: fmt('-*- {user} {message}'), + MessageType.NICK: fmt('<-> {user} is now known as {message}'), + MessageType.MODE: fmt('*** Mode {message} by {user}'), + MessageType.JOIN: fmt('--> {user} ({user.host}) has joined {buffer}'), MessageType.PART: format_part, MessageType.QUIT: format_quit, MessageType.KICK: format_kick, -- cgit v1.2.3-2-gb3c3