Skip to content

Instantly share code, notes, and snippets.

@buchanae
Created June 18, 2013 04:32
Show Gist options
  • Save buchanae/5802689 to your computer and use it in GitHub Desktop.
Save buchanae/5802689 to your computer and use it in GitHub Desktop.
Python string formatter that allows optional keyword placeholders
import string
class FormatKeyError(Exception):
def __init__(self, key):
self.key = key
class OptionalFormatter(string.Formatter):
def get_field(self, field_name, args, kwargs):
try:
return super(OptionalFormatter, self).get_field(field_name, args, kwargs)
except FormatKeyError as e:
return '{' + field_name + '}', e.key
def get_value(self, key, args, kwargs):
try:
return super(OptionalFormatter, self).get_value(key, args, kwargs)
except KeyError:
raise FormatKeyError(key)
foo = OptionalFormatter()
a = 'a_{foo}_{bar}_{0}_{foo.bar}'
print 'final', foo.format(a, bar='bar')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment