Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is sys 'temporarily' imported when print is called?

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)
like image 890
Ma0 Avatar asked Nov 06 '22 23:11

Ma0


1 Answers

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.

like image 164
Daniel Roseman Avatar answered Nov 15 '22 02:11

Daniel Roseman