Lecture 9 - 2 Modules
Lecture 9 - 2 Modules
➢ Technically speaking, a module is nothing more than just a Python file containing
specific functions, variables or classes.
➢ These functions and data types are grouped together to provide some functionality,
which can then be used further inside other programs.
➢ Modules are also a great way to logically organize your code
➢ There are a lot of Python modules - hundreds, maybe even thousands - that you can
use into your programs.
➢ Some of them are default modules, belonging to the Python built-in namespace, and
others can be downloaded, unzipped and installed separately.
➢ You can also create your own Python modules, meaning you can write some code
into a file and then use that code further, inside the application you are building, by
simply importing the file.
Python 3 Modules - Importing
Python 3 Modules - Importing
Now, let's create our own module and see the three ways in which you can import
data from within a module.
Python 3 Modules - Importing
Python 3 Modules - Importing
Python 3 Modules – “import “
Python 3 Modules – “from … import”
➢ Ok, this was the first way of importing code from an external source, a module. Let's
see the second way, now.
➢ You can use the from … import statement to import only some variables or functions
from within a module into your application's namespace, thus reducing the resource
usage of your program.
Python 3 Modules - Importing
Python 3 Modules - “from import *”
The last way of importing is using the from import * method, where the asterisk means
import all names from within that module.
This method is generally not recommended because it overloads the local namespace
of the main application you are importing to. So, if you want to import all the names from
within a module, you should use the import statement instead.
Python 3 Modules - PATH variable
Python 3 Modules - if __name__ == "__main__":
Python 3 Modules - if __name__ == "__main__":
Python 3 Modules - Helpful Functions: dir() and help()
➢ Keep in mind that these two functions, help() and dir() are there to help you get
information about any Python module, so use them whenever you feel uncertain
about a module.
Python 3 Modules - Installing a Non-Default Module