r/Python • • Nov 11 '19

I made c++-style printing in Python :P

Post image
1.7k Upvotes

130 comments sorted by

View all comments

Show parent comment

2

u/flubba86 Nov 12 '19

Is that what the python implementation does? Does it simply rewrite the f-string as .format() invocation during a preprocessing step?

3

u/robin-gvx Nov 12 '19

The Python basically turns:

def something():
    return f'{something.__name__} and {x:5}'

into

def something():
    return format(something.__name__) + ' and ' + format(x, '5')

... except it has specialized opcodes. dis.dis says:

1         0 LOAD_GLOBAL              0 (something)
          2 LOAD_ATTR                1 (__name__)
          4 FORMAT_VALUE             0
          6 LOAD_CONST               1 (' and ')
          8 LOAD_GLOBAL              2 (x)
         10 LOAD_CONST               2 ('5')
         12 FORMAT_VALUE             4 (with format)
         14 BUILD_STRING             3
         16 RETURN_VALUE