Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Templating with both local and global variables using Python `format`

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?

like image 957
kuzzooroo Avatar asked Mar 12 '23 07:03

kuzzooroo


1 Answers

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.

like image 62
user2357112 supports Monica Avatar answered May 02 '23 21:05

user2357112 supports Monica