Skip to content

Commit

Permalink
Use .format_map for safe formatting
Browse files Browse the repository at this point in the history
  • Loading branch information
maxpoletaev committed Apr 17, 2016
1 parent 82f2a92 commit 952e1f0
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 7 deletions.
13 changes: 6 additions & 7 deletions langpack/utils.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,13 @@
from importlib import import_module


class safedict(dict):
def __missing__(self, key):
return '{' + key + '}'


def safe_format(source, **kwargs):
# TODO: perfomance problem
while True:
try:
return source.format(**kwargs)
except KeyError as e:
e = e.args[0]
kwargs[e] = '{%s}' % e
return source.format_map(safedict(**kwargs))


def import_class(path):
Expand Down
3 changes: 3 additions & 0 deletions tests/test_translators.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,9 @@ def test_translate(self):
result = self.translator.translate('hello', name='John')
test.assert_equal(result, 'Hello, John!')

result = self.translator.translate('hello')
test.assert_equal(result, 'Hello, {name}!')

result = self.translator.translate('i_have_apples', count=0)
test.assert_equal(result, 'I have no apples')

Expand Down

0 comments on commit 952e1f0

Please sign in to comment.