From 0bda8c7d89079945c5873f87b8c45e9469a87d38 Mon Sep 17 00:00:00 2001 From: Petr Spacek Date: Fri, 20 Mar 2015 15:55:03 +0100 Subject: [PATCH] Add list pretty-printing for parametrized exceptions. All list entries are converted to strings before the list is printed. I.e. one-item list is printed as 'vm-123.idm.lab.eng.brq.redhat.com. IN NS' instead []. --- dns/exception.py | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/dns/exception.py b/dns/exception.py index 9c578265..0790aa8b 100644 --- a/dns/exception.py +++ b/dns/exception.py @@ -63,10 +63,29 @@ class DNSException(Exception): 'following set of keyword args is required: %s' % ( self.supp_kwargs) + def _fmt_kwargs(self, **kwargs): + """Format kwargs before printing them. + + Resulting dictionary has to have keys necessary for str.format call + on fmt class variable. + """ + fmtargs = {} + for kw, data in kwargs.items(): + if isinstance(data, (list, set)): + # convert list of to list of str() + fmtargs[kw] = list(map(str, data)) + if len(fmtargs[kw]) == 1: + # remove list brackets [] from single-item lists + fmtargs[kw] = fmtargs[kw].pop() + else: + fmtargs[kw] = data + return fmtargs + def __str__(self): if self.kwargs and self.fmt: # provide custom message constructed from keyword arguments - return self.fmt.format(**self.kwargs) + fmtargs = self._fmt_kwargs(**self.kwargs) + return self.fmt.format(**fmtargs) else: # print *args directly in the same way as old DNSException return super(DNSException, self).__str__() -- 2.47.3