DEV Community

João M.C. Teixeira
João M.C. Teixeira

Posted on

Make readable string formatting

I run into this example some days ago while reading someone's else code (variable names were modified to some... or var...):

somejob = "{}{}{}{}{}{}{}{}".format(
    rundir,
    "/",
    fileroot,
    "_",
    someobj.somemethod(run["run_dir"]),
    "_",
    str(some_var),
    "w"
    )
Enter fullscreen mode Exit fullscreen mode

What is wrong with this example?

First, can you actually understand the final shape of the somejob string? For me it is just utterly cryptic. How many {} are there?

So, what is wrong with this case and how can we improve it?

The problem with this string formatting example is that constants are being passed as variables, hiding the shape of the string. It becomes much easier to read if the developer defines the constant sub-strings in the main string:

somejob = "{}/{}_{}_{}w".format(
    rundir,
    fileroot,
    someobj.somemethod(run["run_dir"]),
    str(somevar),
    )
Enter fullscreen mode Exit fullscreen mode

Still, because in this particular case we are using paths, I would go further and advocate for using pathlib.Path instead of the hardcoded /:

# reduce the long call to a short temporary variable
_tmp = someobj.somemethod(run["run_dir"])
somejob = Path(
    rundir,
    f'{fileroot}_{_tmp}_{somevar}w',
    )
Enter fullscreen mode Exit fullscreen mode

I truly believe these modifications improve code reading and facilitates the life of maintainers. What do you think? Does the last example reads better than the first one?

Cheers,

Top comments (0)