Skip to content
Advertisement

Using locals() and format() method for strings: are there any caveats?

Are there any disadvantages, caveats or bad practice warnings about using the following pattern?

JavaScript

I had a very repetitive string generation code to write and was tempted to use this, but something about using locals() makes me uncomfortable. Is there any danger of unexpected behavior in this?

Edit: context

I found myself constantly writing stuff like:

JavaScript

Advertisement

Answer

There is now an official way to do this, as of Python 3.6.0: formatted string literals.

It works like this:

JavaScript

E.g. instead of these:

JavaScript

just do this:

JavaScript

Here’s the official example:

JavaScript

Reference:

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement