[Python-ideas] Let’s make escaping in f-literals impossible

Steven D'Aprano steve at pearwood.info
Thu Aug 18 20:18:30 EDT 2016


On Fri, Aug 19, 2016 at 02:17:29AM +1000, Chris Angelico wrote:

> Format codes are just text, 

I really think that is wrong. They're more like executable code.

https://www.python.org/dev/peps/pep-0498/#expression-evaluation

"Just text" implies it is data:

    result = "function(arg)"

like the string on the right hand side of the = is data. You wouldn't 
say that a function call was data (although it may *return* data):

    result = function(arg)

or that it was "just text", and you shouldn't say the same about:

    result = f"{function(arg)}"

either since they are functionally equivalent. Format codes are "just 
text" only in the sense that source code is "just text". Its technically 
correct and horribly misleading.


> so I should be able to use Unicode
> escapes. Okay. Now let's make that an F-string.
> 
> >>> f"This is a number: {13:0\u07c4}"
> 'This is a number: 0013'

If your aim is to write obfuscated code, then, yes, you should be able 
to write something like that.

*wink*

I seem to recall that Java allows string escapes in ordinary 
expressions, so that instead of writing:

    result = function(arg)

you could write:

    result = \x66\x75\x6e\x63\x74\x69\x6f\x6e\x28\x61\x72\x67\x29

instead. We can't, and shouldn't, allow anything like this in Python 
code. Should we allow it inside f-strings?

    result = f"{\x66\x75\x6e\x63\x74\x69\x6f\x6e\x28\x61\x72\x67\x29}"



-- 
Steve


More information about the Python-ideas mailing list