Last active
April 1, 2020 02:27
-
-
Save gdamjan/3c6fe2b0dfe804de901d6ffc5f30414d to your computer and use it in GitHub Desktop.
safe python micro-template
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
# see also: | |
# - https://docs.python.org/3/library/string.html#string.Template | |
# - https://docs.python.org/3/library/string.html#string.Template.safe_substitute | |
# - https://docs.python.org/3/library/stdtypes.html#str.format_map | |
class _identity_format(dict): | |
def __missing__(self, key): | |
return f'{{{key}}}' | |
class T: | |
def __init__(self, s): | |
self._s = s | |
def __repr__(self): | |
return f'T({self._s!r})' | |
def __call__(self, **kwargs): | |
s = self._s.format_map(_identity_format(**kwargs)) | |
return self.__class__(s) | |
In [2]: s = T('{a} {b} {c}') | |
In [3]: s(a=1) | |
Out[3]: T('1 {b} {c}') | |
In [4]: s(a=1)(b=2) | |
Out[4]: T('1 2 {c}') | |
In [5]: s(a=1)(b=2)(c=3) | |
Out[5]: T('1 2 3') | |
# another approach, this time inherit from str | |
class T2(str): | |
def __repr__(self): | |
return f'{self.__class__.__name__}({self})' | |
def format(self, **kwargs): | |
s = super().format_map(_identity_format(**kwargs)) | |
return self.__class__(s) | |
In [6]: s = T2('{a} {b} {c}') | |
In [7]: s.format(a=1) | |
Out[7]: T2('1 {b} {c}') | |
In [8]: s.format(a=1).format(b=2) | |
Out[8]: T2('1 2 {c}') | |
In [9]: s.format(a=1).format(b=2).format(c=3) | |
Out[9]: T2('1 2 3') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment