Documentation and Type Hints
Learn how to make your code readable for humans and tools
Learning Objectives
- Write descriptive Docstrings for your functions
- Use Type Hints to specify data types
- Understand why code documentation matters
Writing Clear Code
Coding isn’t just about making the computer do something; it’s about telling other humans (including your future self) what your code does. Today we’ll learn two essential tools for professional Python developers: Docstrings and Type Hints.
Docstrings (Documentation Strings)
A Docstring is a special string used as the first statement in a function. It describes what the function does.
|
|
Best Practices:
- Wrap the string in triple quotes
""". - Start with a capital letter and end with a period.
- Be concise but descriptive.
Type Hints
Python is a “dynamically typed” language, meaning variables can change types. However, you can add Type Hints to suggest what type of data a function should expect and return.
|
|
Why use them?
- Clarity: It’s easier to see how to use a function.
- Tooling: Code editors (like VS Code) can show you warnings if you pass the wrong type.
- Auto-complete: Helps your editor suggest correct methods.
Bringing it Together
Professional Python code usually combines both:
|
|
Interactive Practice
Try writing a function is_even that takes an integer and returns a boolean. Add a docstring and type hints!
| Feature | Docstring | Type Hint |
|---|---|---|
| Purpose | Explain logic/use | Specify data types |
| Syntax | """ description """ |
name: type and -> type |
| Execution | Ignored by Python | Ignored by Python |
Quiz
Complete this quiz with a minimum score of 80% to mark Day 11 as complete.
Discussion
Have questions or want to discuss this lesson? Join the conversation below!