On Wed, Oct 07, 2020 at 01:59:24PM +1100, Chris Angelico wrote:
On Wed, Oct 7, 2020 at 1:46 PM Steven D'Aprano
wrote: Recall that we already have literal expressions such as >>> [1, 2, 3] # List literal >>> (1, 2, 3) # Tuple literal >>> {1, 2, 3} # Set literal
Point of terminology: these are not literals (although informally people often call them that, including me on occassion). They are *displays*. [...]
The constants 1, 2 and 3 are literals and the compiler can insert them directly into the code. The list [1, 2, 3] is not, the compiler has to insert code to create the list at runtime.
Be careful with this, as it's only a one-way proof. Any literal can and will be inserted directly as a constant, but there are some non-literals that can be as well:
Sure, I believe that is a function of the keyhole optimizer: it can recognise certain non-literals, such as complex numbers and certain sets and tuples, and pre-generate them at compile time. That's a nice little optimization, especially swapping a mutable set for a frozen set because the compiler sees that the set is only ever read from, never mutated. (I think that was one of Serhiy's optimizations? Whoever it was, thank you.)
Complex numbers and frozen sets don't technically have literals, but thanks to compiler magic, they can appear to. (Also, raw string literals are a thing, but in the compiled code, what you get is just a string object, further confusing this type of proof.)
Raw strings are just an alternative syntax for strings. Just as we can write the same int as `0x4e` or `78`, or the same float as `12e-2` or `0.12`, or the same string as `"""abc"""` or `'\x61\x62\x63'`. They're not different "things", just different ways of writing the same thing.
Although when it comes to f-strings, I honestly don't know what counts as a "literal". Is a single f-string a literal?
An f-string is executable code. py> string = f"π/2 = {print('Calculating...') or __import__('math').atan(float('INF'))}" Calculating... py> string 'π/2 = 1.5707963267948966' Think of it as somewhat analogous to a list comprehension, in that it is an expression that contains executable code that runs at runtime, but it returns a string instead of a list, and rather than a for loop, you can include an arbitrary number of executable expressions. So not much like a list comprehension but a lot like calling eval on string literals :-)
But hey, it wouldn't be python-ideas without pedantry :)
Technically, there are lots of other mailing lists that are equally pedantic *wink* -- Steve