Why are f-strings not printed in Python class methods? - python

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

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.

Related

"Return" does not return anything in Spyder. It works fine with other IDE

I just moved to spyder for Python and the return function doesn't seem to work:
def test():
return 2
test()
The IPython console is empty. If I use print instead of return it works fine. Any idea?
I use python 3.7 with Spyder 4.1.5
Thanks in advance!
The editor is handling your code as a normal python script which means statements ala
test()
don't print their result. Instead you will need to do something with the value you are returning E.g. assign it to a variable or print it.
That you get the result of something displayed immediately is a special function of the python console and not normal python behaviour.
To actually print the result you have to call print(test())
so try this:
def test():
return 2
enter
>>press enter
print(test()
>>press enter

Python function return value vs print [duplicate]

This question already has answers here:
What is the purpose of the return statement? How is it different from printing?
(15 answers)
Closed 6 months ago.
I am exceedingly new to programming, so go easy on me. I use Visual Studio Code as my editor in which I am working on a few python files. When I run the code, say for instance a pandas.dataframe.head() function, it doesn't return anything in the terminal. But when I print the same return value, I am seeing the data from a csv file as expected.
Can anyone explain what is going on?
Is it the case that when a function is run, that the data is stored but not necessarily displayed?
If so, is print the only means of displaying the value of a function when debugging?
Tried googling answers, but don't have clarity yet.
import pandas as pd
df = pd.read_csv('sample.csv')
df.head()
# print(df.head())
Expect some data to be displayed in the terminal
I believe you have learned using either Jupyter or a python console. VS Code is an IDE; it's basically a glorified text editor with features that help developers. You must be used to using python in the console where each line/command it automatically prints the results, whereas you are now likely creating a script and expect the same thing to happen. I don't believe `return has anything to do with what you're asking as it acts the same either way.
EDIT (as I found the actual documentation)
When in an interactive console python calls sys.displayhook after every execution. here's the actual documentation:
If value is not None, this function prints repr(value) to sys.stdout,
and saves value in builtins._. If repr(value) is not encodable to
sys.stdout.encoding with sys.stdout.errors error handler (which is
probably 'strict'), encode it to sys.stdout.encoding with
'backslashreplace' error handler.
sys.displayhook is called on the result of evaluating an expression
entered in an interactive Python session. The display of these values
can be customized by assigning another one-argument function to
sys.displayhook.
Here's my very basic explanation I hope I explain it well enough
In the python console each line/command's results are printed after execution (ie: when you hit enter). (For context, every function/operation implicitly returns None if nothing else is returned, therefore not printed)
When running a python script, nothing will display in the console unless explicitly printed (other cases are uncaught error tracebacks, logging, or writing to stdout, etc...)
So basically the line
df.head()
In a script performs the head function on df and returns the results but nothing happens to the results, unless you assign it to a variable or print it. It's the same as just writing:
"This will only print in a console"
If that line is executed in an interactive console it will call sys.displayhook with the value and print the results:
'This will only print in a console'
But if ran in a script it is essentially a needless line of code unless assigned to a variable.
Basically, the console assumes you want to see results as you code. (basically calling a special print at every line that doesn't print None and isn't called when print is explicitly run) Whereas when running a script it only prints to the console when explicitly asked or other special cases.
Are the first 5 rows of your 'sample.csv' file blank per chance? If not selected, the df.head() returns (https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.head.html) the first 5 rows. So:
import pandas as pd
df = pd.DataFrame({'animal':['alligator', 'bee', 'falcon', 'lion', 'monkey', 'parrot', 'shark', 'whale', 'zebra']})
print(df.head())
animal
0 alligator
1 bee
2 falcon
3 lion
4 monkey
If you want to get a value from a function and use it elsewhere, you should return that value at the end of the function definition. That way when you call the function at some point in your code and you can assign it to a variable which would store the output of the function
For instance
#test.py
def square(i):
return i*i
def main():
eight_square = square(8)
print(eight_square)
Only if you print the output you can actually see it in the terminal when you run python3 test.py. There are other ways to check, what the value is in a variable, for instance using a debugger. Visual Studio can be configured with a debugger if it isn't set up.
A breakpoint is to be set at the location where the value of the variable has to be found and the debugger has to be started.
Reference: Microsoft visual studio docs

Return statement on Python does not seem to work (on Spyder)

I have been using Python for a while and have had no problems with the IDE I've used (I've used WingIDE, now I use Spyder).
But when I started testing some code, which I typed on the editor, today, the return statement does not seem to work. Then I wrote even more basic tests which see what return does, and found out that other functions do not work properly as well.
For example for the function,
def test():
return 2
'''the code below is written in the editor'''
test()
print(type(test()))
print(test())
After running the code on the editor.
test() returns 'nothing' (but it's not actually 'nothing/None/blank space')
type(test()) returns 'nothing' (but it's not actually 'nothing/None/blank space')
print(type(test()) prints 'class 'int' '
print(test()) prints 2
But when I type test() on the console, it returns 2, and when I type type(test()) on the console, it returns class: int.
Note that the same results occur before and after I updated Spyder. And previously, the code in the editor functions the same way as the code in the console, as in typing test() in the editor would have returned 2 when I run the code in the editor.
Python/Spyder hasn't done anything this strange before, what happened?
Here's a visualization. Code in editor
Result after running code in editor displayed in the console
Assuming that the missing output of lines 116-118 is what upsets you:
The editor is handling your code as a normal python script which means statements ala test() don't print their result.
That you get the result of something displayed immediately is a special function of the python console and not normal python behavior.
To actually print the result you have to call print(test()) as you did in line 119-120
Update: After some testing in PyCharm
I got the following behavioir:
Copy&Pasting into the python console:
def test():
return 2
test()
>>press enter
indeed results in a blank output, but this:
def test():
return 2
>>press enter
test()
>>press enter
prints 2 as expected. So my conclusion is that Spyder is maybe not displaying the return value because it was executing a multi-instruction script instead of a single operation.
To expand Fabian's N. answer, Spyder has different evaluation models:
Run file, which is equivalent to python my_file.py.
Run line and Run cell, which copy the contents of a line or a cell to the IPython console and run it there. This model doesn't require adding print's to your code.

Class instance declaration syntax error in Python

I am trying to play with classes in python. I tried to run the following code.
class Abc:
def a(self):
print ("not to be seen")
def b(self):
print("inaccessible is")
self.a
say = Abc()
say.b
I am expecting the output as
inaccessible is
not to be seen
Instead I get the following output:
SyntaxError: invalid syntax
with say highlighted.
Please somebody point out what I am doing wrong.
Edit: I'm using IDLE GUI. Python 33 says the Python docs.
Python likes to make syntax very clear - the ()s after a function are not optional when calling a function without parameters like in some other languages.
You're not calling the functions just 'stating' them.
Try
class Abc:
def a(self):
print ("not to be seen")
def b(self):
print("inaccessible is")
self.a()
say = Abc()
say.b()
Here is the code working.
Syntactically, the code is valid.
You almost had it. You need to call the functions by adding (), like so:
class Abc:
def a(self):
print ("not to be seen")
def b(self):
print("inaccessible is")
self.a()
say = Abc()
say.b()
Actually I'm puzzled why your code throws a syntax error. In Python, it is valid to state a function.
OK, I could reproduce your error by installing idle for Python 3.3.0. I'm sorry that we all suspected that you didn't include the whole error message because IDLE doesn't produce more than a red SyntaxError: invalid syntax. There is nothing wrong with your code, nor your class definition.
I guess, you're just pasting the code as-is into your Python shell window. This way, things won't work because the indentation doesn't get produced correctly.
Try pasting the line class Abc: into your shell window and press Enter. You will see that IDLE automatically indents the next line with a tab. This is the correct indentation for the following line, so when you enter it, you need to paste def a(self): without any extra indentation! If you paste line by line and reduce the indentation by one where needed and terminate your class definition with an extra Enter, your code gets executed correctly.
However, you should better use the following method:
Paste your file into an editor and save it as whatever.py
In IDLE, choose File -> Open and open this file
A new window opens with your source code inside.
Now, press F5 or say Run -> Run Module
Your code will be executed and the result displayed in the Python Shell.
Or, even better, use Python directly in the shell by executing python whatever.py directly.

When running python files in terminal, do return commands not get executed?

I am trying to understand how running a python file in terminal vs running it via IDLE, for instance, may change the way the code is interpreted. I didn't think there would be any difference, but I've been noticing that any "Return" commands in the code get ignored when the code is run on the mac terminal. Why is this the case?
For example, take a code as simple as the following:
def talk(arg):
return arg
talk("Hello!")
Now if I run this in terminal, I would expect it to print out "Hello!", because it would run the function talk on the given arg "Hello!" and return it. I do get the desired result if I change the last line to print talk("Hello!") then it works.
The commands do get executed, but unlike in the REPL, return values in a script are not automatically printed. You will need to use print/print() in order to actually get any output.

Categories

Resources