Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does open(True, 'w') print the text like sys.stdout.write?

I have the following code:

with open(True, 'w') as f:
    f.write('Hello')

Why does this code print the text Hello instead of raise an error?

like image 956
Remi Crystal Avatar asked Sep 29 '15 09:09

Remi Crystal


1 Answers

From the built-in function documentation on open():

open(file, mode='r', buffering=-1... file is either a string or bytes object giving the pathname (absolute or relative to the current working directory) of the file to be opened or an integer file descriptor of the file to be wrapped

That "integer file descriptor" is further described in the os module documentation:

For example, standard input is usually file descriptor 0, standard output is 1, and standard error is 2. Further files opened by a process will then be assigned 3, 4, 5, and so forth.

Since booleans are an int subclass, False can be used interchangeably with 0 and True with 1. Therefore, opening a file descriptor of True is the same as opening a file descriptor of 1, which will select standard output.

like image 102
TigerhawkT3 Avatar answered Nov 15 '22 15:11

TigerhawkT3