[Python-Dev] String Interpolation Best Practices (original) (raw)

Mike Miller python-dev at mgmiller.net
Tue Sep 8 09:17:38 CEST 2015


Hi,

I'd like to collect thinking on best practices that we can use as a style guide for string interpolation. Now that arbitrary expressions are very likely to be included, it is more important to set guidelines than it would otherwise be.

Below is a recent post with some good ideas (though it hopes to restrict expressions, which is not what we're discussing here, but rather creation of a style-guide for code-review a la PEP8).

Would anyone else like to contribute?

-Mike

Recent posts:

On 09/05/2015 02:10 AM, haypo s (Victor Stinner) wrote:

Would it be possible to specify a subset of the Python language allowed in f-string? For example, import or lambda should not be used in a f-string. I'm not convinced that a loop or list/dict/set-comprehension is a good idea neither.

I would prefer to keep as much code as possible outside f-string because:

For example, for me it's a common practice to write a complex list-comprehension on two lines for readability:

newlist = [very_complex_expression(item) for item in oldlist]

sorry, it's hard to indent correctly in a mail client, especially Gmail

Well, I'm not convinced that we need a larger subset than what is allowed currently in str.format(), simple expressions like: obj.attr, obj[index], etc.

I recall horrible examples in the previous mail threads showing how much complex code you can put inside f-string.

Even the following example from the PEP seems too complex to me: print(f"Usage: {sys.argv[0]} [{'|'.join('--'+opt for opt in valid_opts)}]", file=sys.stderr)

Oh, first I read [...] as a list-comprehension :-p But it's part of the output string, not of the Python code...

I prefer to build the second parameter outside the f-string: opts = '|'.join('--'+opt for opt in valid_opts) print(f"Usage: {sys.argv[0]} [{opts}]", file=sys.stderr)



More information about the Python-Dev mailing list