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?
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.
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