
Python Modules and Imports Overview
Learn about importing Python modules, executing modules, utilizing aliases, and exploring module documentation using built-in functions like help() and dir(). Understand the concept of importing modules, the use of the import keyword, and how to make libraries more reusable and organized within your applications.
Download Presentation

Please find below an Image/Link to download the presentation.
The content on the website is provided AS IS for your information and personal use only. It may not be sold, licensed, or shared on other websites without obtaining consent from the author. If you encounter any issues during the download, it is possible that the publisher has removed the file from their server.
You are allowed to download the files provided on this website for personal or commercial use, subject to the condition that they are used lawfully. All files are the property of their respective owners.
The content on the website is provided AS IS for your information and personal use only. It may not be sold, licensed, or shared on other websites without obtaining consent from the author.
E N D
Presentation Transcript
Imports CSEG Python Training, Week 5
Imports Individual Python files are called modules . Modules can be executed from the command-line by giving Python the path to your file. This is what we ve been doing so far. Ex: python your_file.py Modules can also be imported which makes the functions, variables, and classes defined within them available to other modules. This allows you to make reusable libraries and to better organize your applications when they become more complex than a simple script. Modules can be grouped together into a package You use the import keyword to make the contents of a module/package available to your code. import math Notice that did not say math.py, we ll get back to how Python finds modules/packages in a moment.
The . Symbol The . symbol indicates that you re obtaining an attribute contained in something else. An attribute can be a variable, function, or class. So in the previous example, you re obtaining the cos function in the math module. Keep this in mind. This is an important concept when working with objects.
foo.py import_foo.py
buzz.py import_buzz.py
Importing A Module Executes It Importing a module executes the module. This only occurs the first time the module is imported anywhere in your code. When a module is executed by being imported, its __name__ variable will be the name of the file without the .py extension.
help(), dir() When encountering a new package/module, you can open an interactive Python session, import the package/module and then use the help and dir built-in functions to explore the package/module. help(package/module) Allows you to explore documentation for the package/module https://docs.python.org/3/library/functions.html#help dir(package/module) Provides a list of the package/module s contents https://docs.python.org/3/library/functions.html#dir
Aliases Can be kind of cumbersome to type the name of a module/package repeatedly. Can use a different name for a module/package when you import it. Ex: import numpy as np This doesn t change the name everywhere, just the module the import as appears in. Use sparingly to prevent code from becoming unclear.
Common Aliases import numpy as np import matplotlib.pyplot as plt import pandas as pd In general, more descriptive names are greatly preferred. However, an informal style rule has emerged that if you see a very short name like these, it s probably a package/module.
The from Keyword Can use from to import particular functions, variables, sub- modules/packages, classes, from a module/package. Ex: from math import cos Many style guides recommend that you use this for sub-modules/packages only so that it s clear where functions/variables are defined. from numpy import linalg Can combine with as from numpy import testing as npt Never do: from module/package import * This will make it very difficult to understand what your code is doing.
Packages Modules can be grouped together into packages. Any directory with a file named __init__.py in it will become a package __init__.py can have code in it, but it usually just has a version: __version__ = 1.1.0 Use semantic versioning for libraries MAJOR.MINOR.REVISION https://semver.org/ Packages can have sub-packages. Can use this to organize packages with a very large amount of modules. It s rare that you ll need this yourself, but large packages such as numpy make use of this.
Importing Inside a Package When a module is inside a package and it imports another module from within the same package, you still specify the full path of the import. EX: import example_package.utilities This is called an absolute import. There are also relative imports but PEP8 encourages the use of absolute imports whenever possible. Absolute imports show you exactly which module is being used. Relative imports are less clear but tend to be more compact. It is probably better to use the from/as keywords and avoid deeply nested package structures rather than using relative imports.
Executable Packages Packages can be made executable. This is useful for making applications that consist of several modules. If you include a file named __main__.py along-side __init__.py, then you can execute a package from the command-line. python example_package __main__.py should only be used to import a module from the package and call its main function. You may need to add . to your PYTHONPATH environment variable to get this to work. I believe this is specifically a quirk when working with Python on Windows but I could be wrong about that.
Can Execute Modules With -m You can execute any module by running Python with the -m argument EX: python -m this EX: python -m json.tool path/to/data.json The __name__ variable in the module will have a value of __main__ .
Using a setup.py Providing a setup.py file alongside a package allows you to install the package into an environment. The setup.py file contains information about the package such as its name, ,who made it, what files are included, and any dependencies it has. We ll cover this in more detail later.
How Does Python Find Modules/Packages? 1. It checks the directory of the script run with the python command. 2. It checks the directories listed in the environment variable PYTHONPATH 3. It checks for modules installed in the current environment. a. Installed by including the package in your environment.yml b. conda install numpy c. If unavailable using conda, can use pip 4. It checks for built-in modules a. https://docs.python.org/3/library/index.html Built-in modules are last. Make sure you don t name your module something that is already in Python (os, sys, math) While you re still learning what built-in modules exist in Python, try importing your desired name before creating your module.
Import Style PEP8 is Python s official, and very general, style guide Other style guides such as Google s style guide provide more detailed recommendations PEP8 recommends that each import appear on its own line unless you re importing multiple things from the same package.
Homework 1. Take a look at Python s built-in packages and skim the documentation for anything that looks interesting: https://docs.python.org/3/library/index.html 2. Open an interactive Python session and use the help() and dir() functions on anything you found interesting in 1. 3. Create a module named hw_functions Make a function in hw_functions named hello_modules that prints Hello modules! In the same directory as hw_functions, create a module named app. Inside app, import hw_functions and call the hello_modules function. Execute app from the command-line.
More Homework 4. Put app and hw_functions in a package named hw_package. Place the app and hw_functions modules in hw_package Correct the imports Make hw_package executable and call app s main function Execute hw_package from the command-line
Example Files You can get copies of the example files with the following command: git clone https://gitlab.com/CSU-CIRA/python_training_resources/imports.git You can also download them from here: https://drive.google.com/drive/folders/1nxLYEBNmRkyADN68wIUH89DlSuPfSHFm?usp=shari ng