Chapter 11
What is a file descriptor, and in what ways can it be handled in Python?
A file descriptor is used as a handle on an opened external file in a program. In Python, a file descriptor is handled by either using open()
and close()
functions or using the with
statement; for example:
f = open(filename, 'r'); ... ; f.close()
with open(filename, 'r') as f: ...
What problem arises when file descriptors are not handled carefully?
Systems can only handle a certain number of opened external files in one running process. When that limit is passed, the handles on the opened files will be compromised and file descriptor leakage will occur.
What is a lock, and in what ways can it be handled in Python?
A lock is a mechanism in concurrent and parallel programming that performs thread synchronization. In Python, a threading.Lock
object can be handled by either using the acquire()
and release()
methods or using the with
statement; for example:
my_lock.acquire(); ... ; my_lock.release()
with my_lock: ...
What problem arises when locks are not handled carefully?
When an exception occurs while a lock is acquired, the lock can never be released and acquired again if it is not handled carefully, causing a common problem in concurrent and parallel programming called deadlock.
What is the idea behind context managers?
Context managers are in charge of the context of resources within a program; they define and handle the interaction of other entities with those resources, and perform cleanup tasks after the program exits the context.
What options does thewith
statement in Python provide, in terms of context management?
The with
 statement in Python offers an intuitive and convenient way to manage resources while ensuring that errors and exceptions are handled correctly. Aside from better error handling and guaranteed cleanup tasks, the with
 statement also provides extra readability from your programs, which is one of the strongest features that Python offers to its developers.