[docs] [issue28612] str.translate needs a mapping example

Cheryl Sabella report at bugs.python.org
Tue Mar 13 19:47:12 EDT 2018


Cheryl Sabella <chekat2 at gmail.com> added the comment:

IDLE just added similar functionality to pyparse (issue 32940) using:

    class ParseMap(dict):
        def __missing__(self, key):
            return 120 # ord('x')

    # Map all ascii to 120 to avoid __missing__ call, then replace some.
    trans = ParseMap.fromkeys(range(128), 120)
    trans.update((ord(c), ord('(')) for c in "({[")  # open brackets => '(';
    trans.update((ord(c), ord(')')) for c in ")}]")  # close brackets => ')'.
    trans.update((ord(c), ord(c)) for c in "\"'\\\n#") # Keep these.

    code = code.translate(trans)

Of course, all that is probably too much for a docs example, but it uses a mapping without the side effect of defaultdict.  I wonder if defining the dict subclass with __missing__ and then the example of keeping only lowercase letters would work for the docs?

----------
nosy: +csabella

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue28612>
_______________________________________


More information about the docs mailing list