In addition to the programming language there is usually code (functions, etc.) written by others and provided for anyone to use.
These provided items go by different names:
- Modules (Python)
- Libraries (C++)
- Packages (Java)
- Frameworks, more extensive sets of items, various languages
The programmer thus has much pre-written code available and doesn't have to create it herself.
Modules - Importing
To use code in a Python module the code from the module must be imported.
To import a module use:
The contents of the module are:
- Read in
When the Python interpreter executes a function definition this mean that the interpreter retains the code so that it may be called later.
Code like variable assignments, loops, or output will actually be executed.
Modules - Accessing Module Contents
Objects, other than basic objects, have attributes such as methods.
Q: How are the attributes of an object accessed?
A: The dot operator (period).
As we have seen:
a = 'hi there'
b = a.upper() # Use the dot operator
The method upper() is an attribute of string objects.
Modules are objects.
The dot operator is used to access a module's contents. (Example below.)
Put this in a file named mod.py
# This function doesn't do much
print('I have done very little.')
bar = 9684
# Make the contents of the module available
# Call the function in the module
# Access the variable in the module
print("bar = ", mod.bar)
Put this in another file (arbitrarily named) some_other_file.py.
Run the second file some_other_file.py.
Modules - Import Locations
When importing a module the directories searched are those in the list: sys.path
To add to this list do an append. The current directory is in the path.
Import the sys module and show the path: