It's nice in Python to be able to write code like 'Foo bar {some_var} baz'.format(**locals())
. Depending on what other languages you're used to, you may already find that a bit verbose, but what about when you want to pull in global variables as well? The best I can do is this:
GLOBAL_VAR = "Hello"
def func():
local_var = "world!"
print("{GLOBAL_VAR} {local_var}".format(**dict(locals(), **globals())))
func()
That format(**dict(locals(), **globals())))
is quite a mouthful. Is there a more succinct way to do string templating when I want to replace both global and local variables by name?
In 3.6, you'll finally get syntax-level support for string interpolation:
f"{GLOBAL_VAR} {local_var}" # No format(), locals(), or globals()!
As of this writing, 3.6 isn't here yet, though.
In 3.5, you can unpack two dicts for keyword arguments in the same function call:
"{GLOBAL_VAR} {local_var}".format(**globals(), **locals())
3.5 is here, but maybe you're not using it, or you have to support older Python versions.
In Python versions below 3.5, there isn't really anything more succinct.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With