-3

I would like to understand why f-strings do not print output in class methods. I would like to use their concise syntax for making breakpoints.

MWE:

class FStringTest:
    def test(self):
        print('why does this work')
        f'but not this'

print(FStringTest().test())
f'yet this works'

Output:

why does this work
None
yet this works
  • You need to return the string you want to use outside the class method, i.e. `return f'but not this'` – Mirac7 Aug 18 '20 at 21:01
  • 5
    The REPL is the one printing the value of your expression. If you ran that as a script, neither one would print anything. – Ry- Aug 18 '20 at 21:01
  • Have you tried regular strings in the same situations? You will find that you get the output only if it's the very last statement of your program. to prove this, type `True` as the last line of your program after the string. – RufusVS Aug 18 '20 at 21:02
  • `f'yet this works'` Does not print anything. It only gets shown because you've entered it to the interactive interpreter (=Python shell / REPL). – ruohola Aug 18 '20 at 21:03

1 Answers1

1

Are you running this in Jupyter or an interactive python shell? Because if you were, then the 'P' in REPL, which stands for print (R=READ,E=EVALUATE,P=PRINT,L=LOOP), will print the yet this works automatically for you without you explicitly calling the print function.

So:

why does this work

This is what the print inside your method returns.

None

You're seeing this because you're printing the value that your test() method is returning, and since it happens that it returns nothing (no return) it gives you this 'None' value.

yet this works

This is just what the REPL echoing back to you.

Note: Save this as a python script (.py) and try running it in an IDE like VSC, or via the command line using py <script_name>.py, it will not show you that last line of output.

Ahmed Alhallag
  • 311
  • 2
  • 11