point8 / data-science-learning-paths

Practical data science courses
Other
23 stars 3 forks source link

🤖 Add typing hints examples in "Python" notebook #17

Open clstaudt opened 8 months ago

clstaudt commented 8 months ago

Issue Description

The notebook currently lacks a section on type hints, which are a significant feature of modern Python programming for static type checking and code clarity.

Proposed Change

Example Implementation

## Type Hints in Python

Type hints are a feature in Python that allow you to specify the expected data types of variables, function arguments, and return values. While type hints are not enforced at runtime, they provide developers with a clear contract of what a function expects and returns. They are especially helpful for larger codebases, static type checking, and improving IDE support with autocompletion and linting.

Here's how you can add type hints to your Python code:

### Basic Type Hints

```python
# Specifying the data type of a variable
age: int = 25

# Adding type hints to function parameters and return type
def greet(name: str) -> str:
    return f"Hello, {name}!"

Advanced Type Hints with Collections

from typing import List, Dict

# Specifying a list of integers
numbers: List[int] = [1, 2, 3, 4, 5]

# Defining a dictionary with string keys and float values
prices: Dict[str, float] = {'apple': 0.5, 'banana': 0.75}

Functions with Type Hints

from typing import Tuple

# A function that returns a tuple of a string and an integer
def get_data() -> Tuple[str, int]:
    return "data", 42

More examples


from typing import Set, Tuple

# A set of unique strings
usernames: Set[str] = {'user1', 'user2', 'admin'}

# A tuple with mixed data types
person_info: Tuple[str, int, bool] = ('Alice', 30, True)
``