bembry.org
Home / Technology / Python / Notes

Lesson 15 Notes: Modules and Shelves

  • The Problems
    • Code is getting very long.
      • With hundreds of lines, it's easy to get lost
      • When working with partners, it is hard to work on a long body of code.
      • Be nice to break code into smaller, independent files
    • Cannot save data structures
      • If you create a dictionary, we know how to save it as a text file, but we can't read it in as a dictionary.
      • It would be nice to save lists as lists, dictionaries as dictionaries, and so forth and get them back again easily.
  • Breaking Up Code
    • Code can be broken into separate files called "modules".
    • You have already used a lot of modules that come with Python (string, random, time, etc.).
    • To create a module, just type your Python code and save it as usual.
    • Your saved module can be imported and used like any other Python module.
  • Creating a Module
    • Write reusable code.
    • Code should be primarily functions or classes
    • Avoid having variables or commands outside function definitions
    • Functions can require values from the calling program
    • Save code as a regular .py file.
    • In main program, import module and use it
  • Adding New Directory to Path
    • Python only looks inside certain directories for modules.
    • Most built-in modules are saved in c:\python\lib
    • If you save your module in a different place, you will need to add the new directory to sys.path.
    • To edit sys.path, in the interactive interpreter type:
      > > >import sys
      > > >sys.path #prints current directories in path list
      > > >sys.path.append("k:\\mydirectory\\subdir")
    • Be sure to use double back-slashes
    • Change name of directory to the directory you want to add.
  • Making Modules User Friendly
    • Comments in triple-quotes are used to add documentation to your code.
    • Example:
      def my_function(x,y):
          """my_function (first name, last name) """
    • Be certain to use three quotes at beginning and end
    • Do NOT make this a "print" line.
    • Text in triple quotes should explain what the function, class, or module does.
  • Using a Module
    • In main program, include command to import the module.
    • When calling a module function, use its fully qualified name:
      my_module.my_function(name1, name2)
      my_module.another_function()
  • Module Tricks
    • A module can be run as an independent program if you include the following line at the end:
      if __name__ == '__main__':
          run_function()
    • Substitute "run_function()" for the name of the main function in the module.
  • Preserving Python Data
    • Two main methods for preserving data:
    • pickle module:
      Stores python data structures in a binary file. Limited to only one data structure per file.
    • shelve module:
      Stores Python data structures, but allows more than one data structure and can be indexed by a key.
  • How to Shelve
    • Import shelve module
    • Open a shelve file
    • Assign an item, by key, to the shelve file
    • To retrieve, open the shelve file and access item by key
    • shelve works like a dictionary, you add, access and remove items by using their key.
    • shelve works like a dictionary, you add, access and remove items by using their key.
  • Shelve Example
      import shelve
      colors = ["green", "red", "blue"]
      states = ["TN", "KY", "MS"]
      shelf = shelve.open('filename')
      # To shelve an item
      shelf['colors'] = colors
      shelf['ST'] = states
      # Now, to get it back
      newitem = shelf['colors']
      # And close it up
      shelf.close()
  • Other shelve functions
    • To get a list of all the keys available in a shelve file, use the keys() function:
      list = shelf.keys()
    • To delete an item, use the del function
      del shelf('ST')
    • To see if a key exists, use has_key():
      if shelf.has_key('ST'): print "yep"
  • Review
    • How do you create a module?
    • If a module is saved in my folder, but cannot be imported correctly, what might be the problem?
    • What advantage is there in using the shelve module over saving data to a text file?
    • What advantage is there in using the shelve module over saving data to a text file?
    Restricted access