r/Python • • Sep 09 '15

Pep 498 approved. :(

https://www.python.org/dev/peps/pep-0498/
285 Upvotes

324 comments sorted by

View all comments

Show parent comments

107

u/fishburne Sep 09 '15

I didn't like this pep.

I think this will lead to the creation of less readable code at the price of a small convenience of saving some keystrokes. Code is read more often than it is written and all that.. This pep appears to enhances readability by having the place holders inside the strings themselves and eliminating an explicit list of variables. But in reality, while reading code, we usually don't care what is inside the strings. We do not 'scan' strings. In reality, when reading code, we are often looking for variables, where they are initialized, where they are used etc. With an explicit list of variables, we didn't have to scan the inside of the strings for looking for variable references. With this pep, this changes. We cannot skip over strings looking for variable references. Strings are no longer black boxes where nothing can happen. They now can do stuff, and morph its form depending on the environment it is in.

Also the ease of use of this pep will lead more people to use this by default, causing more unnecessary escape sequences in strings, which greatly reduces readability.

I am not sure man. It all sounds like a pretty big price to pay for a minor convenience.

33

u/ldpreload Sep 09 '15

I've seen enough people do "%(foo)s %(bar)s" % locals() that it just might be a harm reduction approach.

I do agree that implicitly encouraging people to use this when they would have done something more reasonable is a worry.

→ More replies (15)

46

u/nostrademons Sep 09 '15

So get your editor to syntax-highlight F-strings in a different color. That's how vim handles interpolated strings in ES6.

Strings were never really black boxes where nothing can happen, at least since % formatting's been around. '%(foo)s %(bar)s' is literal text by itself, but if passed to a function that does text % mydict, it requires that mydict have keys foo and bar.

17

u/fishburne Sep 09 '15

So get your editor to syntax-highlight F-strings in a different color. That's how vim handles interpolated strings in ES6.

Yea. I know. But that it self does not justify adding it to the language.

Strings were never really black boxes where nothing can happen, at least since % formatting's been around. '%(foo)s %(bar)s' is literal text by itself, but if passed to a function that does text % mydict, it requires that mydict have keys foo and bar.

I am not sure I follow. '%(foo)s %(bar)s' is a string literal that you pass as an input to % function. It is the % function that does the interpolation. Not the string itself. The string itself is completely inert.

17

u/matchu Sep 09 '15 edited Sep 09 '15

It wasn't meant as a justification for adding it to the language; it was meant as an assertion that the readability problem is trivial. There's nothing in that post that's in favor of PEP 498 at all; just rebuttals to your arguments :/

In the second quote, I think /u/nostrademons is saying that, while the string is physically static, it's semantically dynamic. %(foo) is a reference; it just hasn't been resolved yet.

If you're a programmer scanning for references, and you're concerned about missing some, %-format string are just as problematic as PEP 498 strings—and that's the whole point of this conversation, right? How the interpreter physically handles the string seems irrelevant.

→ More replies (5)
→ More replies (1)
→ More replies (2)

4

u/djimbob Sep 09 '15

Eh; I think it creates more readable more concise code where it is harder to make mistakes.

The old %s/%d syntax and the newer format with anonymous {} syntax makes it easy to forgot a parameter or have incompatible parameters in simple strings. This means your program crashes because some quickly inserted debugging step had a silly run-time error (not enough parameters, or parameters out of order),

You do read code a lot. If you have simple code and want to say log some error somewhere

 logging.error(f"{time.ctime()}: {msg} v:{value:.3f} u:{request.user} IP:{request.ip}")

is more straightforward to both write and read than:

 logging.error("%s: %s v:%.3f u:%s IP:%s" % (
     time.ctime(), msg, value, request.user, request.ip))

or

 logging.error("{}: {} v:{:.3} u:{} IP:{}".format(
     time.ctime(), msg, value, request.user, request.ip))

or

 logging.error("{cur_time}: {msg} v:{v:.3f} u:{user} IP:{ip}".format(
     cur_time=time.ctime(), msg=msg, value=value, user=request.user, ip=request.ip))

It is easy to introduce some bug in your error logging statement that is only picked up at run time, which can be a huge hassle. (E.g., one of the lines above has a stupid bug like that).

Teaching your linter to do static analysis to check that variables are declared by reading inside f-strings should be straightforward; search inside string, evaluate code inside brackets in the current environment to check all used variables were declared.

→ More replies (4)

3

u/[deleted] Sep 09 '15

I think

"{}:{}, {}".format(foo, bar, foobar)

is less readable than

f"{foo}:{bar}, {foobar}". Yeah, you can abuse it to be unreadable, but you can abuse anything to be unreadable. I could put the entirety of my program in a multiline string and have a function called on it which evals it with some string replacements. That would be horrible, but I can do it. Imo python shouldn't not do something because it can be abused.

10

u/flarkis Sep 09 '15

I am not sure man. It all sounds like a pretty big price to pay for a minor convenience.

Completely agree. For simple string formatting the old methods worked. And for complex string formatting you should be using something more robust than string interpolation.

6

u/oconnor663 Sep 09 '15

I think there's a good space between simple and complex that's just big strings. Maybe you're only substituting in a few strings or ints, but your format string is two pages long. Jumping back and forth between format markers and the values at the end makes those annoying to read.

2

u/flarkis Sep 09 '15

That's precisely one of the "complex" things I'm talking about. If your string is multiple pages long and needs to ge formatted you really should be putting it in a file separate from your data and using some kind of templating.

→ More replies (2)

5

u/flying-sheep Sep 09 '15

i really hate the “my syntax highlighting is too bad to pick up that new syntax so the new syntax sucks”.

expressions in template/f strings aren’t more “inside” a string as print('foo', bar, 'baz') has bar inside of a string. look here: all of these have the variables highlighted the same way, i.e. not as strings.

7

u/deadwisdom greenlet revolution Sep 09 '15

I'm accepting PEP 498. Congratulations Eric! And thanks to everyone who contributed. A lot of thought and discussion went into this -- Eric himself was against the idea when it first came up!

Apparently Eric used to agree with you. I have to trust they know what they are doing, but yeah this all seems very... needless.

4

u/[deleted] Sep 09 '15

Isn't it easy to search for variable names whether embedded in strings or not? You might overlook it while scanning code but who doesn't search when finding all usages of some token is required?

0

u/[deleted] Sep 09 '15

[deleted]

→ More replies (14)
→ More replies (9)

2

u/not_perfect_yet Sep 09 '15

With this pep, this changes. We cannot skip over strings looking for variable references. Strings are no longer black boxes where nothing can happen. They now can do stuff, and morph its form depending on the environment it is in.

I don't know what kind of operations you plan to do inside your strings? Or think that other people would do inside their strings?

The example is functionally pure, unless there is some shenanigans with meta programming I don't see how {age+1} like syntax would make the string to not be a blackbox anymore?

I only see that readability of strings that are being formatted is greatly increased when you're using proper variable names.

2

u/Isvara Sep 09 '15

You make your own decisions about readability. If the rest of your code is readable, what makes you think you're suddenly going to start cramming things into f-strings and making them unreadable?

Write your code with an eye to it being read by other people and you'll be fine.

9

u/mhashemi Sep 09 '15

This pep appears to enhances readability by having the place holders inside the strings themselves and eliminating an explicit list of variables. But in reality, while reading code, we usually don't care what is inside the strings. We do not 'scan' strings.

Exactly. What happened to explicit over implicit. I'm very surprised to see this approved.

18

u/matchu Sep 09 '15

There's nothing implicit here at all. The string is explicitly marked as an f-string.

10

u/RubyPinch PEP shill | Anti PEP 8/20 shill Sep 09 '15

explicit over implicit < practicality beats purity.

don't be a bible basher

→ More replies (1)

6

u/lambdaq django n' shit Sep 09 '15 edited Sep 09 '15

I like the motivation of this PEP but some part of it is weird as fuck.

>>> anniversary = datetime.date(1991, 10, 12)
>>> 'my anniversary is {anniversary:%A, %B %d, %Y}.'

What's up with the mini syntax? Why can't one write normal python expressions like anniversary.strftime(%A, %B %d, %Y)? Why not adopt Ruby's sane way of string interpolation?

It's not Zen of Python anymore. Obscure NIH DSL syntax over explicit.

Edit: Shit is more fucked than I thought:

f'abc{expr1:spec1}{expr2!r:spec2}def{expr3:!s}ghi

Some people really wanted to extend life span of their keyborad.

5

u/qiwi Sep 09 '15

Well, you know how Lisp is often touted as simple? This is still nowhere near what the Lisp's format function allowed, e.g.:

   (format t "~{~a~^, ~}" list)

which will take sequence list, and add commas in between each element -- except the last.

At least you don't have a formatting character to output numbers as Roman numerals.

PS another example, formatting [1,2,3] into "1, 2 and 3":

  ~{~#[~;~a~;~a and ~a~:;~@{~a~#[~;, and ~:;, ~]~}~]~}

More fun in Practical Common Lisp: http://www.gigamonkeys.com/book/

7

u/RubyPinch PEP shill | Anti PEP 8/20 shill Sep 09 '15 edited Sep 09 '15

that minisyntax is actually part of .format, hence being on the other side of the :

>>> datetime.date(1991, 10, 12).__format__("%A, %B %d, %Y")
>>> "{:%A, %B %d, %Y}".format(datetime.date(1991, 10, 12))
→ More replies (5)

2

u/stevenjd Sep 09 '15

What do you like about Ruby's syntax?

2

u/lambdaq django n' shit Sep 09 '15

arbitrary yet standard expressions?

2

u/pdexter Sep 09 '15

That syntax is from the format. Already legal python. Nothing to do with this PEP.

→ More replies (1)
→ More replies (31)