==
tests "value equality"is
tests "identity equality"def
is actually a statement
It is strongly suggested that scripts are importable as modules and that modules can be executable.
For this reason, most modules adhere to form of defining one or more importable functions, followed by a postscript to facilitate execution as a script
import sys
from urllib.request import urlopen
# 'http://sixty-north.com/c/t.txt'
def fetch_words(url):
story = urlopen(url)
story_words = []
for line in story:
line_words = line.decode('utf8').split()
for word in line_words:
story_words.append(word)
story.close()
return story_words
def print_items(items):
for item in items:
print(item)
def main(url):
words = fetch_words(url)
print_items(words)
if __name__ == '__main__':
main(sys.argv[1])
import
examples# importing multiple objects from module
from cli_args_words import (fetch_words, print_words)
# import everything from module
from cli_args_words import *
sys
module called argv
(a list of strings)$ python /_demos/story_words/cli_args_words.py http://sixty-north.com/c/t.txt
however, can no longer be run from REPL env, since url
in main()
is unlikely to get any value from sys.argv[1]
2nd refactor fixes this issue to make main()
accept the url
param
Additional inspiration:
☯️ Moment of Zen ☯️ "Sparse is better than dense" Two between functions That is the number of lines PEP8 recommends
literal strings which document functions, modules, and classes
must be FIRST statement in blocks for these constructs
convention for docstrings is documented in PEP257, though not widely adopted
Sphinx: tool for creating HTML documentation from Python docstrings
form from Google's Python Style Guide is used in this course
#!/usr/bin/env python
$ chmod +x /path/to/script.py