Table of contents
{: .text-delta } 1. TOC {:toc}Python Functions, Modules, and Libraries¶
Let's clear the confusion about Python libraries, modules, functions & methods.
Functions and Methods¶
Functions¶
A function is a block of code inside def. Functions are stanalone and indepandant. Here’s a simple function:
Methods¶
A methods are like functions, but they are connected to an object; Methods are present inside a class and when you call them you need to give them live objects of that class.
Here's an example of a method:
class Greeter:
def __init__(self, name):
self.name = name
def greet(self):
return f"Hello, {self.name}!"
greeter = Greeter("Alice") # Creating a live object of a class
print(greeter.greet()) # Giving the method a live object
def:
. E.g. math.sqrt()
, os.path.exists()
, json.loads()
__init__
method for initialization. E.g. list.append()
, str.upper()
, dict.items()
Modules¶
A python module is a .py
file. E.g. ikea.py
. It contains classes, functions and other code. You import it using import ikea
and get all the funcs clases in your new code.
Usually the module name and its filename is same. math module is math.py
Example of a Module:
Create a file named ikea.py
:
ikea.py
becomes ikea module. You can import it now to use it:
import moduleName
vs from moduleName import funcName
¶
import module
:from moduleName import funcName
from ikea import add # Imports only a function(s) from that module
add() #To use. Directly use the function. No ModuleName required.
import module
vs from module import *
¶
import module
:- Imports the entire module with the packing: Module is imported as a complete package(with the cover).
- Access: To use the modules functions you need to add
moduleName.
. - Example:
-
Benefits: Keeps the module's namespace separate, which helps avoid naming conflicts. It also makes it clear where each function, class, or variable comes from.
-
from module import *
: - Imports all functions, classes etc. but without the package(cover) directly into the current namespace: This means each function, class, and variable in the module is individually imported into your current namespace(cover is not imported).
- Access: You can use the imported items directly without the module name prefix.
- Example:
- Issues: Can create naming conflict. Say, you created your own
sqrt
function, Python won't know whichsqrt
to use(math's or yours?). This makes it hard to trace where functions, classes, or variables come from, especially in large programs or many modules.
Libraries¶
A library is a collection of modules. Libraries contain similar module for similar tasks.
Example: Using the pandas
Library¶
The pandas
library has many modules for data manipulation and analysis. When you import pandas
, you get access to all its tools.
import pandas as pd # Importing the entire library!
data = {
'Name': ['Alice', 'Bob', 'Charlie'],
'Age': [25, 30, 35]
}
df = pd.DataFrame(data) # Here, `DataFrame` is a module in the `pandas` library
print(df)
Conclusion¶
- Python Universe: The entire Python ecosystem.
- Galaxies: Libraries (e.g., NumPy, Pandas).
- Solar Systems: Modules within libraries.
- Planets: Classes within modules.
- Moons: Methods within classes.
- Satellites: Functions within modules.
- Asteroids/Comets: Variables within functions or classes.
Installing Libraries in Python¶
To install libraries in Python, you typically use the `pip` command from the command prompt or terminal. `pip` is a package manager for Python that allows you to install, upgrade, and manage libraries.
Installing Libraries from the Command Prompt¶
To install a library, open your command prompt or terminal and type:
For example, to install thepandas
library, you would type: Installing Libraries Inside Code¶
You can also install libraries from within your Python code using the os
module to run shell commands:
However, it is more common to use the command prompt for installing libraries to avoid unnecessary overhead in your scripts.
Sources to Find Libraries¶
You can find Python libraries on the Python Package Index (PyPI) website, pypi.org. PyPI is the official repository for Python packages where you can search for and learn about different libraries.
Managing libraries When Sharing Python Code¶
When you write a Python script that relies on external libraries, you need to ensure those libraries are installed on any system where the script will run. Here’s how you can manage dependencies using a `requirements.txt` file.
Creating a Python Script with Dependencies¶
Suppose you have a Python script named data_analysis.py
that uses the pandas
library:
# data_analysis.py
import pandas as pd
data = {
'Name': ['Alice', 'Bob', 'Charlie'],
'Age': [25, 30, 35]
}
df = pd.DataFrame(data)
print(df)
Creating a requirements.txt
File¶
To manage dependencies, create a requirements.txt
file that lists all the libraries your script needs. You can generate this file automatically if the libraries are already installed in your environment:
This command will create a requirements.txt
file with contents similar to:
Installing Dependencies on Another System¶
When someone else wants to run your data_analysis.py
script on another system, they should follow these steps:
-
Clone or Copy the Project: Get the script and the
requirements.txt
file onto their system. -
Create a Virtual Environment (Optional but Recommended):
Newer systems(linux versions) now makes it mandatory to install venv.
-
Install Dependencies:
This command reads the requirements.txt
file and installs all the listed libraries. This way the script will not run into can't find xxx error.
Example Workflow¶
Let me explain it with a sample workflow:
- On the Development System:
# Create the Python script
echo "
import pandas as pd
data = {
'Name': ['Donald', 'Biden', 'Mia Khalifa'],
'Age': [25, 30, 35]
}
df = pd.DataFrame(data)
print(df)
" > data_analysis.py
# Install pandas if not already installed
pip install pandas
# Generate requirements.txt
pip freeze > requirements.txt
-
On the Target System:
Using a terminal or CMD.
# Clone project or copy files scp user@development_system:/path/to/project/* /path/to/local/directory/ # Go to the project directory cd /path/to/local/directory # (Optional) Create venv(virtual env) python -m venv myenv source myenv/bin/activate # If you use windows you may have to use `myenv\Scripts\activate` # Install required libraries pip install -r requirements.txt # Run the script python data_analysis.py
This is how you ensure that all necessary dependancies are available on the other machine where the script is re-run.