Hmm, okay. Seems easy enough. Let’s try this.
name = "Subject Name Here" # from Subject Hometown Here
args = {"name": name}
print("Hello, {name}!".format_map(args))
greeting = "Hello, {name}!"
print(greeting.format_map(args)
I’m sure you can figure that one out, simple matter of static analysis. All you have to do is trace through everywhere that a string gets used. I’m sure that won’t cause any weird, confusing, annoying edge cases. It’ll be fine. Ooh, what about this one?
def fmt(msg, **args):
return msg.format_map(args)
def main():
name = input(fmt("Enter your name: "))
print(fmt("Hello, {name}!", name=name))
Hmm. Does it become any harder if we destubbify that function a bit?
# this would probably come from a YAML file or something
# assume that, after parsing, it's a mapping from original English to
# the chosen language - even if that's English
from translations import english as lang
def L10N(msg, **args):
msg = lang.get(msg, msg)
return msg.format_map(args)
def main():
name = input(L10N("Enter your name: "))
print(L10N("Hello, {name}!", name=name))
Remember, you’re asking the Python compiler to magically know which ones should be compiled as evaluated expressions and which ones should be literals. This can be incredibly significant:
def outer(name):
print(name)
msg1 = "I am {name}!"
def inner():
msg2 = "And I am {name}!"
print(msg1.format(name="inner"))
print(msg2.format(name="inner"))
return inner
outer()()
You can’t change the way a string is parsed on the basis of whether its format method will, in the future, be called. You definitely can’t change the way it’s parsed on the basis of whether the format method MIGHT be called, unless you have some way of absolutely guaranteeing what every module does - including modules you haven’t seen yet. In most of these examples, you could break this across two modules, making the task pretty much impossible.
This kind of thing might (MIGHT) be possible in C++, with all of the potential confusion being resolved at link time. I don’t think it will work in Python. Feel free to prove me wrong, though.