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?

def buildString(user, name = 'john', age=22):
    userId = user.getUserId()
    return "Name: {name}, age: {age}, userid:{userId}".format(**locals())

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:

"{name} {age} {userId} {etc}...".format(name=name, age=age, userId=userId, etc=etc)

Advertisement

Answer

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

It works like this:

f'normal string text {local_variable_name}'

E.g. instead of these:

"hello %(name) you are %(age) years old" % locals()
"hello {name} you are {age} years old".format(**locals())
"hello {name} you are {age} years old".format(name=name, age=age)

just do this:

f"hello {name} you are {age} years old"

Here’s the official example:

>>> name = "Fred"
>>> f"He said his name is {name}."
'He said his name is Fred.'
>>> width = 10
>>> precision = 4
>>> value = decimal.Decimal("12.34567")
>>> f"result: {value:{width}.{precision}}"  # nested fields
'result:      12.35'

Reference:

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