Organizing our module into functions

Let's organize our words module using functions.

First we'll move all the code except the import statement into a function called fetch_words(). You do that simply by adding the def statement and indenting the code below it by one extra level:

from urllib.request import urlopen


def fetch_words():
with urlopen('http://sixty-north.com/c/t.txt') as story:
story_words = []
for line in story:
line_words = line.decode('utf-8').split()
for word in line_words:
story_words.append(word)

for word in story_words:
print(word)

Save the module, and reload the module using a fresh Python REPL:

$ python3
Python 3.5.0 (default, Nov 3 2015, 13:17:02)
[GCC 4.2.1 Compatible Apple LLVM 6.1.0 (clang-602.0.53)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import words

The module imports, but the words are not fetched until we call the fetch_words() function:

>>> words.fetch_words()
It
was
the
best
of
times

Alternatively we can import our specific function:

>>> from words import fetch_words
>>> fetch_words()
It
was
the
best
of
times

So far so good, but what happens when we try to run our module directly from the operating system shell?

Exit from the REPL with Ctrl+D from Mac or Linux or Ctrl+Z for Windows, and run Python 3 passing the module filename:

$ python3 words.py

No words are printed. This is because all the module does now is to define a function and then immediately exit. To make a module from which we can usefully import functions into the REPL and which can be run as a script, we need to learn a new Python idiom.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset