Exercises

  1. Basics, import. With your favorite text editor, write a Python module called mymod.py, which exports three top-level names:

    • A countLines(name) function that reads an input file and counts the number of lines in it (hint: file.readlines() does most of the work for you)

    • A countChars(name) function that reads an input file and counts the number of characters in it (hint: file.read() returns a single string)

    • A test(name) function that calls both counting functions with a given input filename

    A filename string should be passed into all three mymod functions. Now, test your module interactively, using import and name qualification to fetch your exports. Does your PYTHONPATH include the directory where you created mymod.py ? Try running your module on itself: e.g., test("mymod.py"). Note that test opens the file twice; if you’re feeling ambitious, you might be able to improve this by passing an open file object into the two count functions.

  2. from/from. Test your mymod module from Exercise 1 interactively, by using from to load the exports directly, first by name, then using the from* variant to fetch everything.

  3. __main__. Now, add a line in your mymod module that calls the test function automatically only when the module is run as a script. Try running your module from the system command line; then import the module and test its functions interactively. Does it still work in both modes?

  4. Nested imports. Finally, write a second module, myclient.py, which imports mymod and tests its ...

Get Learning Python now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.