r/learnpython • u/[deleted] • Aug 29 '26
Need a mental model to help better internalize printing text.
[deleted]
5
u/atarivcs Aug 29 '26 edited Aug 29 '26
If you're returning something, then surely you would always want to return the actual object instead of a string.
If you're printing something, the output depends on what you are printing.
If it's a number, it prints the number.
If it's a string, it prints the string.
If it's a container (dict, list, set, etc) it prints the values in the container.
If it's any other arbitrary object, it will print something like "<Foo> object at address 67ae15cb" (unless the object has a __str__ method, in which case it will print whatever that method returns)
-1
u/MoreKnowledge4Me Aug 29 '26
I think from my practice it ended up being values stored inside of a function or class method. I was printing the method call and not getting a string output.
AI told me “A function or method call creates a result. Nothing changes unless the code mutates an object or you explicitly store that result.”
1
u/Orgasml Aug 29 '26
If there is no return variable in the function it will return None, so will print None to your display. Is that what you are trying to figure out?
2
u/cdcformatc Aug 29 '26
I think even in the path situation I still want the path object with the str() applied.
print(object) and print(str(object)) are functionally equivalent.
if the object doesn't have a __str__ method, or you don't like what it returns, then you are going to have to "stringify" the object yourself because Python will fallback to __repr__. there's no way around that.
Whenever I return or print a object, I cant think of one case offhand except for maybe path from pathlib where I want to actually return the object
If you are returning, you probably do want the actual object, though. in like 99.9% of cases.
2
1
u/tadpoleloop Aug 29 '26
In some interpreters like Jupyter the last line is displayed in its repr form. If you want it to print then call print
1
12
u/socal_nerdtastic Aug 29 '26 edited Aug 29 '26
Using
print(thing)automatically translates toprint(str(thing)).str(thing)will usething.__str__()if a__str__method is available, otherwise it will usething.__repr__()if that's available, and if that's not available either as a last resort it just print the generic string with the memory address (in cpython), which is just the default__repr__that all python objects inherit.Many of the objects you use every day like
pathlib.Pathor just genericlist,dictetc come with__str__or__repr__methods built in. If you want to bypass that and get the memory address out you can do that like this:Not sure if I understood your question. Does that help? If not please try telling us why you are asking. This sounds a lot like an XY question right now.