Code: Select all
class Name:
def __init__(self, name):
self.name = name
self.capitalized = name.capitalize()
def __str__(self):
return self.name
"hello, {name}!".format(name=Name("bob")) # hello, bob!
"greetings, {name.capitalized}!".format(name=Name("bob")) # greetings, Bob!
# but, if no name kwarg is given...
"hello, {name}!".format(age=34) # hello, {name}!
"greetings, {name.capitalized}!".format(age=34) # greetings, {name.capitalized}!
Ich habe mehrere Lösungen für Stackoverflow gefunden, aber keine davon kann mit Attributen umgehen. Meine erste Lösung war diese:
Code: Select all
class Default(dict):
"""A dictionary that returns the key itself wrapped in curly braces if the key is not found."""
def __missing__(self, key: str) -> str:
return f"{{{key}}}"
Code: Select all
class CustomFormatter(string.Formatter):
def get_value(self, key, args, kwargs):
try:
value = super().get_value(key, args, kwargs)
except KeyError:
value = f'{{{key}}}'
except AttributeError:
value = f'{{{key}}}'
return value
formatter.format("hello, {name}!", name=Name("bob")) # hello, bob!
formatter.format("greetings, {name.capitalized}!", name=Name("bob")) # greetings, Bob!
formatter.format("hello, {name}!", age=42) # hello, {name}!
formatter.format("greetings, {name.capitalized}!", age=42) # AttributeError: 'str' object has no attribute 'capitalized'
Code: Select all
"hello, {name}!".format(name=Name("bob")) # hello, bob!
"greetings, {name.capitalized}!".format(name=Name("bob")) # greetings, Bob!
# but, if no name kwarg is given...
"hello, {name}!".format(age=34) # hello, {name}!
"greetings, {name.capitalized}!".format(age=34) # greetings, {name.capitalized}!