f-string syntax deficiency?

Roel Schroeven roel at roelschroeven.net
Tue Jun 6 10:41:16 EDT 2023


Op 6/06/2023 om 16:08 schreef Chris Angelico:
> On Wed, 7 Jun 2023 at 00:06, Neal Becker <ndbecker2 at gmail.com> wrote:
> >
> > The following f-string does not parse and gives syntax error on 3.11.3:
> >
> > f'thruput/{"user" if opt.return else "cell"} vs. elevation\n'
> >
> > However this expression, which is similar does parse correctly:
> >
> > f'thruput/{"user" if True else "cell"} vs. elevation\n'
> >
> > I don't see any workaround.  Parenthesizing doesn't help:
> >  f'thruput/{"user" if (opt.return) else "cell"} vs. elevation\n'
> >
> > also gives a syntax error
>
> Is this a problem with the f-string, or with the expression
> opt.return? That's a keyword.
'return' being a keyowrd is definitely going to be the problem.

Neal, I assume you're using 'opt.return' also outside of that f-string. 
Does that work? How did you manage to do that? I tried to make a simple 
class with an attribute called 'return', but that already fails with a 
syntax error.

(Recently there has been an effort to provide clearer and more useful 
error messages; this seems to be a case where there is still room for 
improvement: "SyntaxError: invalid syntax" doesn't immediately remind me 
of that fact that 'return' is a keyword and therefor can't be used as an 
attribute.)

-- 
"Don't Panic."
         -- Douglas Adams, The Hitchhiker's Guide to the Galaxy



More information about the Python-list mailing list