How can I format string using computed key-value mapping?

Question:

I need something like that: '{abc} {def}'.format(lambda key: compute_value(key)). It looks like I need to implement a custom mapping for that:

class Vars(collections.abc.Mapping):
    def __getitem__(self, key):
        return 'abc'
    def __len__(self):
        pass
    def __iter__(self):
        pass

Now if I try '{abc} {def}'.format(**Vars()) I get TypeError: iter() returned non-iterator of type 'NoneType' error. For some reason it tries to iterate through my mapping.

Is there a simple way to format string using computed key-value mapping?

Asked By: ababo

||

Answers:

I think you can use str.format_map(), this way each item is fetched as needed and not expanded to kwargs via **

'{abc} {def}'.format_map(Vars())

Results in:

'abc abc'

Note: Python 3.2+ only

Answered By: vaizki
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.