Lesson 10: Modules, sorting, and lambda functions
This week we discuss modular programming and how to organize your code logically by writing Python modules. The Python docs define a module as “a file that contains Python definitions and statements” that can be imported by another Python file in order to access the module’s functionality.
We will also introduce you to create and pass an anonymous lambda
functions to the built-in
sorted()
function and list
method sort()
in order to better control how the data is sorted.
Readings
Below are a set of readings that you should consider reviewing. Note that the Real Python articles referenced below may require signing up for a free account.
1.0 Required
Lisa Tagliaferri, How to Write Modules in Python 3 (DigitalOcean, Feb. 2017).
Lisa provides a short introduction covering how to create, import, and access modules located in other directories.
David Fundakowski, How to Use sorted() and sort() in Python (Real Python, May 2019).
Discusses how to sort data structures employing the built-in function sorted()
, sort methods like
list.sort()
, as well as employing the key
argument to control how the data should be sorted
using a lambda
expression or user-defined function.
2.0 Recommended
Below are a set of useful readings that you should consider reviewing. Note that the Real Python articles referenced below may require signing up for a free account.
Andre Burgaud, How to Use Python Lambda Functions (Real Python, June 2019).
Comprehensive discussion.
Mbithe Nzomo, Absolute vs Relative Imports in Pythons (Real Python, September 2018).
Discusses Python’s import system and use of absolute and relative paths when crafting an import
statement.
John Sturtz, Python Modules and Packages - An Introduction (Real Python, April 2018).
After reading Lisa’s short article, read John’s article. John provides more depth to the discussion.
Read the following sections:
- Python Modules: Overview
- The Module Search Path
- The import Statement
You can skip the other sections including the section on how to create Python packages.