Explain Codes LogoExplain Codes Logo

Proper indentation for multiline strings?

python
multiline-strings
readability
docstrings
Anton ShumikhinbyAnton Shumikhin·Aug 12, 2024
TLDR

To properly indent multiline strings in Python, you can use the textwrap.dedent() function along with triple quotes """:

from textwrap import dedent message = dedent("""\ First line. Second line. Third line.""") print(message)

This recipe allows your multiline string to align with the left edge of your code block, keeping the intended formatting.

Employ parentheses for better readability

When dealing with multiline strings that span several lines of code, an effective approach is to utilize parentheses () to seamlessly join the lines. This method fosters readability and improves the ability to maintain the code:

# Construct a simple SQL query query = ( "SELECT id, name FROM users " # We need user IDs and names "WHERE active = 1 " # But only for active users "ORDER BY name" # As alphabetically ordered as an encyclopedia )

This way, Python assembles these pieces together, sans additional characters, upholding a neat indentation and a clear direction.

Ensuring strong and stylish docstrings with PEP 257

By adhering to PEP 257 recommendations, you can deliver docstrings that serve as a source of truth for your code and are meticulously aligned and formatted.

def my_function(): """ A simple function. Returns: None """ pass

To further enhance the docstrings, one can use inspect.cleandoc when it's vital to preserve relative indentation along with maintaining structure within function:

import inspect def my_function(): doc = inspect.cleandoc("""\ A function upholding simplicity. This function wouldn't lift a finger. I mean, returns None! Returns: None""") print(doc)

Handling bulky text

When a multiline string transforms into a saga, it's a smart idea to separate it out into an external .txt file. This keeps the main script congestion-free, and your code turns as readable as your favorite book:

with open('epic_saga.txt', 'r') as file: epic_saga = file.read()

Multiline string cleaning drive

Python offers built-in functions like .strip() or you can create custom functions to trim off the unwanted parts from your multiline strings, giving them a neat makeover:

s = """ Line one with whitespace. Line two with more whitespace. Line three.""".strip() print(s) # Ah, now this looks as neat as your desktop after spring cleaning!

Leveraging external modules

Sometimes, standard library may feel like the ordinary fries, and you might crave the variety of seasoned fries. That's where external modules come in, such as dedent function from matplotlib, offering a different flavor of utility:

from matplotlib.cbook import dedent text = dedent(""" Here lies an example text. Misaligned but eager to learn Pythonic ways. """)

Intuitive indentation decisions

Situations can demand indenting strings or vice versa. These choices are more dependent on the context than on a universal principle. Sometimes, making the code legible may prioritize over strict alignment to style guides. So, always consider various trade-offs before making indentation decisions.

The '\n' secret

There might be cases where manual insertion of \n characters provides greater control over line breaks in multiline strings. This can be beneficial when dealing with dynamically built strings, or when you're copying and pasting multiline strings:

error_message = ( "An error occurred in the application.\n" # As unexpected as an alien invasion + "Please contact support with this error code:\n" # Not your superhero hotline + "Error 42\n" # If only you knew the question! )

Though not the perfect fit for every scenario, manual insertion of newlines gives you the <<bullhorn_on>> power of precision <<bullhorn_off>>.