32

I want to provide automatic string formatting in an API such that:

my_api("path/to/{self.category}/{self.name}", ...)

can be replaced with the values of attributes called out in the formatting string.


How do I extract the keyword arguments from a Python format string:

"non-keyword {keyword1} {{escaped brackets}} {} {keyword2}" => 'keyword1', 'keyword2'
2
  • I guess you don't want to use format? Commented Sep 23, 2014 at 13:57
  • @user189 I will use <str>.format(**kwargs). My question is about building that kwargs dictionary automatically. Commented Sep 23, 2014 at 14:06

4 Answers 4

72

You can use the string.Formatter() class to parse out the fields in a string, with the Formatter.parse() method:

from string import Formatter

fieldnames = [fname for _, fname, _, _ in Formatter().parse(yourstring) if fname]

Demo:

>>> from string import Formatter
>>> yourstring = "path/to/{self.category}/{self.name}"
>>> [fname for _, fname, _, _ in Formatter().parse(yourstring) if fname]
['self.category', 'self.name']
>>> yourstring = "non-keyword {keyword1} {{escaped brackets}} {} {keyword2}"
>>> [fname for _, fname, _, _ in Formatter().parse(yourstring) if fname]
['keyword1', 'keyword2']

You can parse those field names further; for that you can use the str._formatter_field_name_split() method (Python 2) / _string.formatter_field_name_split() function (Python 3) (this internal implementation detail is not otherwise exposed; Formatter.get_field() uses it internally). This function returns the first part of the name, the one that'd be looked up on in the arguments passed to str.format(), plus a generator for the rest of the field.

The generator yields (is_attribute, name) tuples; is_attribute is true if the next name is to be treated as an attribute, false if it is an item to look up with obj[name]:

try:
    # Python 3
    from _string import formatter_field_name_split
except ImportError:
    formatter_field_name_split = str._formatter_field_name_split
from string import Formatter

field_references = {formatter_field_name_split(fname)[0]
 for _, fname, _, _ in Formatter().parse(yourstring) if fname}

Demo:

>>> from string import Formatter
>>> from _string import formatter_field_name_split
>>> yourstring = "path/to/{self.category}/{self.name}"
>>> {formatter_field_name_split(fname)[0]
...  for _, fname, _, _ in Formatter().parse(yourstring) if fname}
{'self'}

Take into account that this function is part of the internal implementation details of the Formatter() class and can be changed or removed from Python without notice, and may not even be available in other Python implementations.

Sign up to request clarification or add additional context in comments.

8 Comments

Just curious, Martijn, would you use a simple str.replace() or re.sub() (or something entirely different) to generate the new string?
@mtik00: depends on the use case; sometimes a str.replace() is just what is called for.
Thanks for your input! In this specific case, I would have used str.replace() in a loop; nice and simple.
@mtik00: this is not a simple replace job however; the str.format() format allows for nested placeholders too, for example.
When does the parse() function return a None as field? I'm not able to understand the documentation :(
|
6

UPDATE: _formatter_parser() is a private method and hence not available anymore for python >= 3.8 or even earlier

Building off Martijn's answer, an easier format for the comprehensive list that I've used is:

>>> yourstring = "path/to/{self.category}/{self.name}"
>>> [x[1] for x in yourstring._formatter_parser() if x[1]]
['self.category', 'self.name']

It's functionally exactly the same, just much easier to digest.

4 Comments

I can't find any documentation for _formatter_parser()! is it an alias for Formatter.parse()?
It may as well be afaik, here is the relevant section for Formatter.parse() github.com/python/cpython/blob/…, as well as the relevant section for _formatter_parser() itself: github.com/python/cpython/blob/…
As of Python 3.11.2, _formatter_parser() is not longer a method of str. You can replace it with Formatter().parse(yourstring).
_formatter_parser() also not available for python 3.8.8 -> AttributeError: 'str' object has no attribute '_formatter_parser'
3

If all placeholders are named, a special dictionary could be used to intercept which keys are tried to be accessed and logged to an array.

def format_keys(str_):
    class HelperDict(dict):
        def __init__(self):
            self._keys = []
        def __getitem__(self, key):
            self._keys.append(key)    
    d = HelperDict()
    str_.format_map(d)
    return d._keys

Note that if there are unnamed placeholders, an IndexError will be raised by .format() (tuple index out of range).

1 Comment

A fun idea but it needs some polish. e.g. the None returned by __getitem__ will cause unhandled exception from a format string like 'My {foo} is {bar:03d}'.
0

You can do "path/to/{self.category}/{self.name}".format(self=self). You could thus work with those kwargs in __getattr__.

4 Comments

I don't think this will actually.
You don't think this will actually what?
@JaceBrowning: it'll work; self.__getattr__ will be called for each attribute on self. However, this doesn't help for anything that isn't an attribute on self.
@MartijnPieters thanks for the clarification. This answer is almost exactly what I need, but I expect there will be non-attribute keywords as well.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.