I’m finding this to be a difficult question to put into words, hence the examples. However, I’m basically being given arbitrary format strings, and I need to go (efficiently) fetch the appropriate values from a database, in order to build a relevant mapping object dynamically.
Given a format string expecting a mapping object, e.g.:
>>> 'Hello, %(first-name)s!' % {'first-name': 'Dolph'}
'Hello, Dolph!'
I’m looking for an implementation of ‘infer_field_names()’ below:
>>> infer_field_names('Hello, %(first-name)s! You are #%(customer-number)d.')
['first-name', 'customer-number']
I know I could write regex (or even try to parse exception messages!), but I’m hoping there’s an existing API call I can use instead..?
Based on the string Formatter docs, I thought this would work:
>>> import string
>>> format_string = 'Hello, %(first-name)s! You are #%(customer-number)d.'
>>> [x[1] for x in string.Formatter().parse(format_string)]
[None]
But that doesn’t quite return what I would expect (a list of field_names, per the docs).
When using the
%operator to format strings, the right operand doesn’t have to be a dictionary — it only has to be some object mapping the required field names to the values that are supposed to be substistuted. So all you need to do is write a class with an redefined__getitem__()that retrieves the values from the database.Here’s a pointless example:
prints