The __name__  type and executing modules from the command line

The Python runtime system defines some special variables and attributes, the names of which are delimited by double underscores. One such special variable is called __name__, and it gives us the means for our module to determine whether it has been run as a script or, instead, imported into another module or the REPL. To see how, add:

print(__name__)

Add the end of your module, outside of the fetch_words() function.

Speaking Python aloud
You will from time to time need to talk about Python aloud, and you’ll invariably find that — like any programming language — Python has  elements which don't lend themselves to human speech. The special names denoted by double underscores are a prime example because they're ubiquitous in Python and, frankly, you can only say "double underscore name double underscore" so many times before you start to think about changing careers. To help alleviate this situation, a common practice among Pythonistas is to use the term "dunder" as short hand for "surrounded by double underscores". So, for example, __name__ would be pronounced "dunder name". As an added bonus, saying "dunder" is fun! Try it and I guarantee you'll feel better.

First of all, let's import the modified words module back into the 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
words

We can see that when imported __name__ does indeed evaluate to the module's name.

As a brief aside, if you import the module again, the print statement will not be executed; module code is only executed once, on first import:

>>> import words
>>>

Now let's try running the module as a script:

$ python3 words.py
__main__

In this case the special __name__ variable is equal to the string main which is also delimited by double underscores. Our module can use this behavior to detect how it is being used. We replace the print statement with an if-statement which tests the value of __name__. If the value is equal to main then our function is executed:

if __name__ == '__main__':
fetch_words()

Now we can safely import our module without unduly executing our function:

$ python3
>>> import words
>>>

If we can usefully run our function as a script:

$ python3 words.py
It
was
the
best
of
times
..................Content has been hidden....................

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