yasar
yasar

Reputation: 13768

Should I close makefile'ed socket and it is original socket independently?

Python docs says that;

socket.makefile([mode[, bufsize]])
Return a file object associated with the socket. (File objects are described in File Objects.) The file object references a dup()ped version of the socket file descriptor, so the file object and socket object may be closed or garbage-collected independently.

Does it mean I have to close both socket and file like this?

conn = socket.create_connection((addr,port))
myfile = conn.makefile()
myfile.close()
conn.close()

Or closing one is sufficient? If so, does it matter which one I close and which one I don't?

Upvotes: 2

Views: 988

Answers (1)

user355252
user355252

Reputation:

As the documentation says, both objects are independent. The underlying connection is closed only if all file descriptors related to it are closed. You must close both. Use the with statement to manage such resources.

Upvotes: 2

Related Questions