To answer this question, you need to define "graceful." You can think of several factors:
- Is the code short, easy to remember, easy to write, and understandable?
- Does it reuse logic (i.e. following the DRY principle)?
- Does it use exactly the same parsing logic?
Unfortunately, the formatting "%" for strings is implemented in the PyString_Format subroutine in stringojbect.c. This procedure does not provide APIs or interceptors that allow access to the parsed form of the format string. It just creates a result when it parses a format string. Thus, any solution would have to duplicate the parsing logic from subroutine C. This means that DRY is not respected and provides some kind of hacking solution if changes are made to the formatting specification.
The parsing algorithm in PyString_Format involves a rather complicated task, including processing nested brackets in key names, therefore it cannot be fully implemented using a regular expression and the string "split ()" is not used. Unless you copy the C code from PyString_Format and convert it to Python code, I don’t see a remotely simple way to correctly extract the matching key names under all conditions.
So, I came to the conclusion that there is no "graceful" way to get the matching key names for the format string "%" Python 2.7.%
The following code uses a regular expression to provide a partial solution that covers the most common use:
import re class StringFormattingParser(object): __matcher = re.compile(r'(?<!%)%\(([^)]+)\)[-# +0-9.hlL]*[diouxXeEfFgGcrs]') @classmethod def getKeyNames(klass, formatString): return klass.__matcher.findall(formatString)
PS DRY = don't repeat yourself ( https://en.wikipedia.org/wiki/Don%27t_repeat_yourself )
J. beattie
source share