Jump to content

A very important thing for all programmers to know about is requesting and releasing resources


G+_Lee Crocker
 Share

Recommended Posts

A very important thing for all programmers to know about is requesting and releasing resources. Opening files is a classic example: when you "open" a file in whatever programming language, you are asking the system to hold some resources for you, which you will then use, and which you are expected to return when you're done (called "closing" the file). If you fail to properly return a resource that the system has allocated to you, you can cause problems like excessive use of memory (a "memory leak") or denying access to that resource to other programs that may need it.

 

Files are actually pretty forgiving: if you open files and forget to close them, they will all be closed when your program exits. This is why it wasn't a big deal that Dale didn't close the file in his example, because the program exited after doing its work. But this is sloppy, and a bad habit to get into.

 

Especially since Python has features that make it easy to do right: one is the "with" statement. Here's how a Pythonista would read from a file:

 

    with open("myfile", "r") as f:

        lines = f.readlines()

        # do whatever . . .

 

When Python sees this, it will open the file, make the variable "f" point to the open file that you can do things with, and then automatically close the file after the "with" statement completes (that is, after running all the indented lines). This can be used for other resources as well, for example, to open a connection to a database or to request access to draw on a window. The "with" statement ensures that you will politely disconnect or do whatever other cleanup is necessary.

 

You should always use "with" to open files in Python unless you have a very good reason not to (and if you're just learning the language, you'll never have a good reason not to).

Link to comment
Share on other sites

You sure get used to your resource management responsibilities if you coded a lot of C.   These newer languages that do "garbage collection" of memory allocation take a lot of that away.   But there are actual resources that need to be carefully managed.   File handle objects are one sort of that type of resource pool.   Also, database connection objects.

Link to comment
Share on other sites

 Share

×
×
  • Create New...