11

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?

0

1 Answer 1

10

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.

Sign up to request clarification or add additional context in comments.

5 Comments

So what about 0? :)
And does it mean that when you open a file, it will be 3, 4, 5, etc. ?
As it says in the second quote block, 0 is standard input, and sequential integers will be assigned as more files are opened.
@KevinGuan, unless you have file descriptors open that have a fileno of 3, 4 or 5 it obviously won't work. It only works for 0, 1 or 2 because they are stdin, stdout and stderr which are open file descriptors.
@PadraicCunningham, TigerhawkT3 Understand now, thanks :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.