Last active
February 18, 2025 20:28
-
-
Save ariel-co/9698d0e951763e196e2979a10d554f27 to your computer and use it in GitHub Desktop.
string formatter without KeyError
This file contains hidden or 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 | |
| from typing import Callable | |
| class FormatterWithFallback(string.Formatter): | |
| def __init__(self, fallback: str|Callable): | |
| self.fallback=fallback | |
| def get_value(self, key, args, kwds): | |
| try: | |
| return super().get_value(key, args, kwds) | |
| except (KeyError, IndexError): | |
| if isinstance(self.fallback, str): | |
| return self.fallback.format(key) | |
| elif callable(self.fallback): | |
| return self.fallback(key) | |
| def get_param(key): | |
| from getpass import getpass | |
| return ( getpass(f"{key[1:]}? ") if key.startswith('*') | |
| else input(f"{key}? ") ) | |
| print(FormatterWithFallback(get_param).format( | |
| "{0:_<8}, {x:.2f}, {*password}", 'joe', x=10/3)) | |
| # password? | |
| # joe_____, 3.33, sikritpassword | |
| print(FormatterWithFallback("{{?{0}}}").format( | |
| "{0:_<8}, {x:.2f}, {nosuch:10s}", 'joe', x=10/3)) | |
| # joe_____, 3.33, {?nosuch} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment