Welcome to the Zoo Management System! Through managing animals in our zoo, you'll learn the essential concepts of covariance and contravariance in Python's type system.
By completing this tutorial, you'll understand:
- Why variance matters in type systems
- When to use covariance vs contravariance
- How to implement type-safe generic classes in Python
# Install dependencies
pip install mypy
# Run the first practice
python -m practices.lesson1_viewing_animals
# Check your solution with mypy
mypy practices/lesson1_viewing_animals.py
You're a software engineer at a zoo. Your job is to build a type-safe system for managing animals. Through four progressive lessons, you'll discover why Python's variance rules exist and how to use them effectively.
Scenario: Visitors want to view animals in exhibits. A cat exhibit should work anywhere an animal exhibit is expected.
Key Insight: Reading is safe with subtypes → Use covariance
Scenario: Zookeepers feed animals. A handler who can feed any animal should be able to feed cats specifically.
Key Insight: Writing is safe with supertypes → Use contravariance
Scenario: Moving animals between cages. You can't use a cat cage where an animal cage is expected (might put a dog in!).
Key Insight: Read+Write requires exact types → Use invariance
Scenario: Build a complete zoo management system using all three concepts together.
Each lesson contains:
- Broken code with type errors
- Your task: Fix the code to pass mypy checks
- Solution: Check the answer when you're done
Start with Lesson 1 and work your way through. Each lesson builds on the previous one!
practices/
├── lesson1_viewing_animals.py # Covariance practice
├── lesson2_feeding_animals.py # Contravariance practice
├── lesson3_animal_cages.py # Invariance practice
├── lesson4_zoo_system.py # Combined practice
└── solutions/ # Check your answers here
zoo/
└── animals.py # Base classes used throughout
Concept | Use When | Example |
---|---|---|
Covariance | Read-only operations | Exhibit[Cat] → Exhibit[Animal] ✅ |
Contravariance | Write-only operations | Feeder[Animal] → Feeder[Cat] ✅ |
Invariance | Read and write operations | Cage[Cat] → Cage[Animal] ❌ |
Ready to start? Head to practices/lesson1_viewing_animals.py
! 🚀