I was looking at the Python documentation for print
which states:
print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)
As it can be seen, if the file
on which to print is not specified, the default sys.stdout
is used, which got me thinking.
Calling print
definitely does not import sys
in the background, so how does it work?
is sys.stdout
somehow reachable from everywhere?
Example:
I am using PyCharm and I want to create a function that either prints a message text
to a file or to standard output. I began writing:
def my_print(text, file=None):
print(text, file=file if file is not None else ?)
So what goes after else
? sys.stdout
does not work and obviously, I am not interested in the verbose:
def my_print(text, file=None):
if file is None:
print(text)
else:
print(text, file=file)
The other answer points out that print is implemented in C. However, even if it was implemented in Python, that would not mean that sys
was available from everywhere.
Consider this code:
utils.py
import sys
def my_print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False):
file.write(sep.join(objects))
main.py
from utils import print
my_print('foo')
Here sys
is only available within utils, but print will still output to sys.stdout
without it being accessible from main.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With