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?
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
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?
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