Write reliable, maintainable Python code by learning unit testing, code formatting, version control with Git, and using virtual environments like venv and pipenv.
Objective:
Write high-quality Python code that is tested, consistent, version-controlled, and easy to maintain using testing frameworks, formatting standards, Git, and virtual environments.
Topics and Examples:
1. Unit Testing: unittest, pytest
Unit testing ensures your code works as expected.
Example (unittest):
import unittest
def add(a, b):
return a + b
class TestMath(unittest.TestCase):
def test_add(self):
self.assertEqual(add(2, 3), 5)
self.assertEqual(add(-1, 1), 0)
if __name__ == "__main__":
unittest.main()
Example (pytest):
# test_math.py
def add(a, b):
return a + b
def test_add():
assert add(2, 3) == 5
assert add(-1, 1) == 0
# Run: pytest test_math.py
2. Code Formatting: PEP8, Black
- PEP8: Python style guide for readable code
- Black: Automatic code formatter
Example (Black formatting):
# Original
def add( a,b ):
return a+b
# After Black
def add(a, b):
return a + b
3. Version Control with Git/GitHub
Version control helps track changes and collaborate on projects.
Basic Git Commands:
git init # Initialize repository
git add . # Stage changes
git commit -m "Message" # Commit changes
git branch # List branches
git checkout -b new_branch # Create and switch branch
git push origin main # Push changes to GitHub
4. Virtual Environments: venv, pipenv
Virtual environments isolate project dependencies to avoid conflicts.
Using venv:
# Create virtual environment
python -m venv myenv
# Activate environment (Windows)
myenv\Scripts\activate
# Activate environment (Linux/Mac)
source myenv/bin/activate
# Install packages
pip install requests
Using pipenv:
pip install pipenv
pipenv install requests # Install package in pipenv environment
pipenv shell # Activate pipenv shell
This section covers essential Python best practices, including unit testing with unittest/pytest, code formatting with PEP8 and Black, version control with Git/GitHub, and managing project dependencies using virtual environments like venv and pipenv.