1

I accidentally wrote code that effectively did this:

with open(1) as f:
    for line in f:
        print(line)

This did not throw an error on opening 1 (not a string, but an actual integer), and then hung on for line in f. What exactly is happening here, and why does the open not throw an exception?

Note: What I really wrote was with open(filepath) as f:, and due to a bug I accidentally set filepath to an integer. I don't expect this to come up frequently, but I was surprised that I didn't get an error.

Mad Physicist
  • 107,652
  • 25
  • 181
  • 264
supergra
  • 1,578
  • 13
  • 19
  • It did for me: `OSError: [WinError 6] The handle is invalid` –  Sep 25 '20 at 19:22
  • 4
    [docs](https://docs.python.org/3/library/functions.html#open) - "...or an integer file descriptor of the file to be wrapped." – khelwood Sep 25 '20 at 19:24
  • @hippozhipos. Also on Windows, but I got `OSError: [Errno 9] Bad file descriptor`. Same problem, different wrapper – Mad Physicist Sep 25 '20 at 19:34

0 Answers0