From 61b4eefd38ff474684b384d57d388346113d94b4 Mon Sep 17 00:00:00 2001 From: Trygve Aaberge Date: Fri, 22 Sep 2017 16:10:49 +0200 Subject: refactor: Split en/decoding helper into a separate method Separate the code for wrapping a method so arguments and return values are encoded/decoded into a new method in WeechatWrapper. This allowes us to use it outside of __getattr__ as well, so we can handle some specific methods differently. --- wee_slack.py | 20 +++++++++++++------- 1 file changed, 13 insertions(+), 7 deletions(-) diff --git a/wee_slack.py b/wee_slack.py index 90b56ac..d23be42 100644 --- a/wee_slack.py +++ b/wee_slack.py @@ -137,16 +137,22 @@ class WeechatWrapper(object): def __init__(self, wrapped_class): self.wrapped_class = wrapped_class + # Helper method used to encode/decode method calls. + def wrap_for_utf8(self, method): + def hooked(*args, **kwargs): + result = method(*encode_to_utf8(args), **encode_to_utf8(kwargs)) + # Prevent wrapped_class from becoming unwrapped + if result == self.wrapped_class: + return self + return decode_from_utf8(result) + return hooked + + # Encode and decode everything sent to/received from weechat. We use the + # unicode type internally in wee-slack, but has to send utf8 to weechat. def __getattr__(self, attr): orig_attr = self.wrapped_class.__getattribute__(attr) if callable(orig_attr): - def hooked(*args, **kwargs): - result = orig_attr(*encode_to_utf8(args), **encode_to_utf8(kwargs)) - # Prevent wrapped_class from becoming unwrapped - if result == self.wrapped_class: - return self - return decode_from_utf8(result) - return hooked + return self.wrap_for_utf8(orig_attr) else: return decode_from_utf8(orig_attr) -- cgit