Created
June 18, 2013 04:32
-
-
Save buchanae/5802689 to your computer and use it in GitHub Desktop.
Python string formatter that allows optional keyword placeholders
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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