Skip to main content

Command Palette

Search for a command to run...

Python Best Practice: f-string, destructing, ignore value

f-string implementation and printing variable with name and value, applying destructing in multiple variable assignment and ignore value with "_"

Published
3 min read
Python Best Practice: f-string, destructing, ignore value

1. Introduction

Here are some helpful tips for developing in Python.

2. String Interpolation, f-string

2.1. Concartenate string with variable

From Python 3.6, f-string is introduced and it provides a simple and readable way to handle string interpolation.

name = "Fred"
print( f"He said his name is {name}." )
# He said his name is Fred.

width = 10
precision = 4
value = decimal.Decimal("12.34567")
print( f"result: {value:{width}.{precision}}" )  # nested fields
# result:          12.35

Remarks:

  • If you are interested why f-string is better than the old way of string interpolation, please take a look here.
  • This feature does not exists in Python alone. `...${<expression>}...` in Javascript and $"...{<expression>}..." in C# also do the same thing.

2.2. Print variable with name and value

From Python 3.8, f-string supports self-documenting expressions and debugging

It means that if you write print( f"{<expression A>=} )", the output will be <expression A>=expression A's value

user = 'eric_idle'
member_since = date(1975, 7, 31)
print( f'{user=} {member_since=}' )
# user=eric_idle member_since=datetime.date(1975, 7, 31)

theta=30
print(f'{theta=}  {cos(radians(theta))=:.3f}')
# theta=30  cos(radians(theta))=0.866

This is very useful in debugging/logging as you can print out variable and its value during execution.

2.3. Precaution, using ' or " in f-string

Look at the following example:

print(f"{ "a" }")
# SyntaxError: f-string: expecting '}'

SyntaxError occurs since f-string here use double quote " to indicate the string, if you use " insides the {...}, the error will be thrown.

You need to change the inner " --> ':

print(f"{ 'a' }")
# a

3. Multiple Assignment - Destructing

Python supports multiple assignment in a line, like:

x, y = 1, 3

Moreover, Python supports destructing in assignment. for example,

x, y = ( 2, 6 )
# Equals to:
# coordinate = ( 2, 6 )
# x = coordinate[ 0 ]
# y = coordinate[ 1 ]

x, y = [ 2, 6 ]
# Equals to:
# arr = [ 2, 6 ]
# x = arr[ 0 ]
# y = arr[ 1 ]

Destructing is also supported in for loop.

people = [
    ("Bob", 42, "Mechanic"),
    ("James", 24, "Artist"),
    ("Harry", 32, "Lecturer")
]

for name, age, profession in people:
    print(f"{name=}, {age=}, {profession=}")
# name='Bob', age=42, profession='Mechanic'
# name='James', age=24, profession='Artist'
# name='Harry', age=32, profession='Lecturer'

Remarks:

This is a lot better than something like the code below, where we rely on indices instead of good descriptive names. Ref

for person in people:
   print(f"{person[0]=}, {person[1]=}, {person[2]=}")

4. Ignore Value by _

As described in previous chapter, Python supports multiple assignment and destructing. Also, it can have multiple return in function.

Sometimes, we only need some of its outputs and would like to ignore other values. In this case, using _ to mark unnecessary value is the solution for us and can also increase code readibility.

# In below code, we would like to ignore "age"

people = [
    ("Bob", 42, "Mechanic"),
    ("James", 24, "Artist"),
    ("Harry", 32, "Lecturer")
]

name, _, profession = people[ 1 ]
print(name, profession)
# James Artist

for name, _, profession in people:
    print(f"{name=}, {profession=}")
# name='Bob', profession='Mechanic'
# name='James', profession='Artist'
# name='Harry', profession='Lecturer'

def get_multiple_value():
    return "James", 24, "Artist"

name, _, profession = get_multiple_value()
print(name, profession)
# James Artist

Python

Part 4 of 10

Introduce different possibilities in using Python in various areas and also see how far Python can go

Up next

First glimpse into gRPC through Python (Part 2)

Implement grpc with Python with examples and tips