[issue24360] improve argparse.Namespace __repr__ for invalid identifiers.

paul j3 report at bugs.python.org
Wed Jun 3 22:52:07 CEST 2015


paul j3 added the comment:

An alternative would be to wrap a non-identifier name in 'repr()':

    def repr1(self):
        def fmt_name(name):
            if name.isidentifier():
                return name
            else:
                return repr(name)
        type_name = type(self).__name__
        arg_strings = []
        for arg in self._get_args():
            arg_strings.append(repr(arg))
        for name, value in self._get_kwargs():
            arg_strings.append('%s=%r' % (fmt_name(name), value))
        return '%s(%s)' % (type_name, ', '.join(arg_strings))

This would produce lines like:

    Namespace(baz='one', 'foo bar'='test', 'x __y'='other')
    
    Namespace(a=1, b=2, 'double " quote'='"', "single ' quote "="'")

    Namespace(')'=3, a=1)

    Namespace(a=1, 'b=2), Namespace(c'=3)

With names that are deliberately messy, it is hard to say which is clearer.

----------

_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue24360>
_______________________________________


More information about the Python-bugs-list mailing list