0% found this document useful (0 votes)
60 views

Python Fundamentals: Modularity

The document discusses Python modularity and how modules, scripts, and programs work. Modules can be imported and contain functions and code executed on import. Scripts can be directly executed and have access to command line arguments through sys.argv. Docstrings document code and comments begin with #.

Uploaded by

VFisa
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
60 views

Python Fundamentals: Modularity

The document discusses Python modularity and how modules, scripts, and programs work. Modules can be imported and contain functions and code executed on import. Scripts can be directly executed and have access to command line arguments through sys.argv. Docstrings document code and comments begin with #.

Uploaded by

VFisa
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

Python Fundamentals

Modularity

Robert Smallshire Austin Bingham


@robsmallshire @austin_bingham
[email protected] [email protected]
Presenter
fred
def _int32_to_bytes(i):
"Convert an integer to four bytes in little-endian format."
return bytes( (i & 0xff,
i >> 8 & 0xff,
i >> 16 & 0xff,
i >> 24 & 0xff) )

def _bytes_to_int32(b):
"Convert a bytes object containing four bytes into an integer."
return b[0] | (b[1] << 8) | (b[2] << 16) | (b[3] << 24)
jim
def console_card_printer(passenger, seat, flight_number, aircraft):
output = "| Name: {0}" \
" Flight: {1}" \
" Seat: {2}" \
" Aircraft: {3}" \
" |".format(passenger, flight_number, seat, aircraft)
banner = '+' + '-' * (len(output) - 2) + '+'
border = '|' + ' ' * (len(output) - 2) + '|'
lines = [banner, border, output, border, banner]
card = '\n'.join(lines)
print(card)
print()
sheila
def make_flight():
def fetch_words(): f = Flight("BA758", Aircraft("G-EUPT", "Airbus A319",
with urlopen('http://sixty-north.com/c/t.txt') as story: num_rows=22, num_seats_per_row=6))
story_words = [] f.allocate_seat('12A', 'Guido van Rossum')
for line in story: f.allocate_seat('15F', 'Bjarne Stroustrup')
line_words = line.decode('utf8').split() f.allocate_seat('15E', 'Anders Hejlsberg')
for word in line_words: f.allocate_seat('1C', 'John McCarthy')
story_words.append(word) f.allocate_seat('1D', 'Richard Hickey')
return story_words return f

def print_items(items):
for item in items:
print(item)

def main():
url = sys.argv[1]
words = fetch_words(url)
print_items(words)
>>> import fred
fred «uses» >>> import jim
«executes» >>>
$ python3 fred.py 42
$

«uses»
«uses» «uses»

jim
sheila
import fred
import fred «uses»
import sheila
Special attributes in Python are
delimited by double underscores

__name__
Evaluates to “__main__” or the actual module name
depending on how the enclosing module is being used.
The Python Execution Model

When are functions defined?

What happens when a module is imported?


module,
script
or
program?
Python module

Convenient import with API

Python script
Convenient execution from
command line

Python program

Perhaps composed of many


modules
Python module
Python script
Convenient execution from
command line
Convenient import with API

Python program
Perhaps composed of many
modules
Python program
Perhaps composed of many
modules
Setting up a main() function
with a command line argument
ed co m m a nd lin e a rg um en t p ars in g:
Advanc
• Python Standard Library: argparse
y op ti on s s uc h as d o c o p t
• Many third -p a rt
Moment of Zen

Sparse is better
than dense
Two between functions
That is the number of lines
PEP eight recommends
"""Documenting your code.

Using docstrings.
"""
Docstring conventions
• PEP 257 – not widely adopted
• reStructuredText / Sphinx
• Google Python Style Guide
# Comments
#!
PyLauncher
• executable is py.exe and is on the PATH
• associated with *.py files
• parses Unix-style shebangs to locate the correct
Python interpreter version
• #!/usr/bin/env python3 works on Windows
f rom
l ab le
i
Ava hon 3.3
Pyt
Modularity – Summary
 Python code is placed in *.py files called “modules”
 Modules can be executed directly with
python module_name.py
 Brought into the REPL or other modules with
import module_name
 Named functions defined with the def keyword
def function_name(arg1, argn):
 Return from functions using return keyword with optional parameter
 Omitted return parameter or implicit return at end returns None
 Use __name__ to determine how the module is being used
 If __name__ == "__main__" the module is being executed
 Module code is executed exactly once, on first import
 def is a statement which binds a function definition to a name
Modularity – Summary

 Command line arguments are accessible through sys.argv


 The script filename is in sys.argv[0]
 Docstrings are a standalone literal string as the first statement
of a function or module
 Docstrings are delimited by triple quotes
 Docstrings provide help()
 Comments begin with # and run to the end of the line
 A special comment on the first line beginning #!
controls module execution by the program loader

You might also like