Skip to content

Commit 036dca8

Browse files
committed
test deployment
1 parent ef8853d commit 036dca8

17 files changed

+418
-155
lines changed
Lines changed: 52 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,58 +1,89 @@
1+
# Mypy Static Type Checker
12

2-
# Mypy Static Type Checker
3-
4-
In this tutorial, we'll explore the benefits of using Mypy, a powerful static type checker for Python. While code editors can catch some mistakes when annotating object types, Mypy ensures a more comprehensive check of types, especially in complex scenarios.
3+
Mypy is a powerful static type checker for Python that ensures type correctness and helps catch errors early in the development process. By integrating Mypy into your workflow, you can validate the type annotations in your code and avoid potential runtime issues.
54

65
## Installation
76

8-
To get started with Mypy, install it using the following command:
7+
To start using Mypy, install it via pip:
98

109
```bash
1110
pip install mypy
1211
```
1312

14-
Once installed, you'll immediately notice syntax highlighting in your code editor, providing warnings for incompatible types.
13+
Once installed, Mypy integrates seamlessly with your development environment, providing syntax highlighting and warnings for type mismatches.
1514

16-
## Usage in Code Editors
15+
## Enhancing Code Editors
1716

18-
While some code editors may not display Mypy warnings by default, you can enhance your development environment by installing the Mypy plugin. Here's a quick guide for PyCharm users:
17+
While some code editors provide basic support for type annotations, you can enhance the experience by installing the Mypy plugin. Here's how to set it up in PyCharm:
1918

20-
1. Navigate to **Settings**.
21-
2. Go to **Plugins**.
19+
1. Open **Settings**.
20+
2. Navigate to **Plugins**.
2221
3. Search for "Mypy" in the marketplace.
23-
4. Install the plugin (choose the one with more downloads and better ratings).
22+
4. Install the plugin (prefer the one with higher downloads and better ratings).
23+
24+
This plugin provides real-time feedback on type annotations directly within the editor.
2425

25-
## Running Mypy
26+
## Running Mypy from the Command Line
2627

27-
To ensure a thorough check of your code, run Mypy from the command line:
28+
To perform a thorough check of your code, run Mypy via the command line:
2829

2930
```bash
3031
mypy your_script.py
3132
```
3233

33-
This command will identify any type mismatches and provide detailed warnings.
34+
This command analyzes the specified script and reports any type mismatches or errors. It provides detailed warnings to help you fix issues promptly.
35+
36+
## Practical Examples
3437

35-
### Example: List Type Check
38+
### Example 1: List Type Check
3639

37-
Consider a list variable defined to contain strings:
40+
Consider the following example where a list is defined to contain strings:
3841

3942
```python
4043
my_list = ["cup", "apple"]
4144
```
4245

43-
Mypy will catch issues if you attempt to insert incompatible types like booleans or other lists containing integers.
46+
If you attempt to insert incompatible types, such as a boolean or a list containing integers, Mypy will catch these issues and raise warnings. For instance:
4447

45-
### Example: Optional Arguments
48+
```python
49+
my_list.append(42) # Mypy will flag this as an error
50+
```
4651

47-
Mypy is especially helpful in catching errors related to optional arguments in functions. For instance:
52+
### Example 2: Optional Arguments
53+
54+
Mypy is particularly useful for handling optional arguments in functions. For example:
4855

4956
```python
50-
def my_function(default: int = None):
57+
from typing import Optional
58+
59+
def my_function(default: Optional[int] = None):
5160
# Your function logic here
61+
pass
5262
```
5363

54-
Mypy will warn that the default value has the type of `None`, but the argument is annotated as `int`. To resolve this, either provide a default value that is not `None` or explicitly annotate the argument as `Optional`.
64+
In this case, Mypy will correctly interpret the type of `default` as `Optional[int]` (which can be `int` or `None`). If you forget to annotate the type explicitly, Mypy will warn you about potential type mismatches.
65+
66+
### Example 3: Type Mismatches in Return Values
67+
68+
Mypy can also validate return types in functions:
69+
70+
```python
71+
from typing import List
72+
73+
def get_items() -> List[str]:
74+
return ["item1", "item2", 42] # Mypy will flag the integer as an error
75+
```
76+
77+
If the return value does not match the specified type, Mypy will raise an error.
78+
79+
## Benefits of Mypy
80+
81+
1. **Enhanced Code Quality**: By ensuring type correctness, Mypy helps reduce bugs and improves maintainability.
82+
2. **Early Error Detection**: Mypy catches type-related issues during development, preventing potential runtime errors.
83+
3. **Improved Readability**: Explicit type annotations make your code easier to understand and maintain.
84+
4. **Seamless Integration**: Mypy integrates with popular code editors and CI/CD pipelines.
5585

5686
## Conclusion
5787

58-
In conclusion, integrating a static type checker like Mypy into your projects is crucial for ensuring type correctness. While code editors can be helpful, Mypy provides an extra layer of validation, catching errors that may be overlooked. Regularly running the `mypy` command helps maintain code quality by detecting and fixing type-related issues early in the development process.
88+
Integrating Mypy into your Python projects is a best practice for maintaining type correctness and improving code quality. While modern code editors provide some level of type checking, Mypy offers a comprehensive validation layer that catches subtle issues. Regularly running the `mypy` command helps identify and resolve type-related problems early, ensuring your code remains robust and error-free.
89+

webpage/docs/python-guide/10_Advanced/02_Walrus_Operator.md

Lines changed: 31 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,16 @@
1+
# The Walrus Operator in Python
12

2-
# Walrus Operator
3+
The walrus operator (`:=`), introduced in Python 3.8, enables assignment and evaluation in a single expression. This feature reduces redundant lines of code and can enhance readability in specific scenarios. However, using it requires careful consideration to maintain code clarity.
34

4-
In recent years, Python introduced a new operator known as the walrus operator (`:=`). This operator allows for the creation of a variable and the evaluation of an expression simultaneously, reducing the need for additional lines of code. However, it's crucial to note that the walrus operator was introduced in Python 3.8, so using it in earlier versions will result in errors.
5+
## Prerequisites
6+
7+
Ensure your Python version is 3.8 or later to use the walrus operator. Attempting to use it in earlier versions will result in syntax errors.
58

69
## Function Example: Calculating Description of a List of Numbers
710

8-
Let's explore how to use the walrus operator in a function that calculates the length, sum, and mean of a list of integers. Initially, we'll write the function without the walrus operator:
11+
The walrus operator can simplify calculations and variable assignments. Here’s a step-by-step example:
12+
13+
### Without the Walrus Operator
914

1015
```python
1116
def description(numbers):
@@ -20,7 +25,7 @@ def description(numbers):
2025
return details
2126
```
2227

23-
Now, let's use the walrus operator to simplify the code within the dictionary creation:
28+
### With the Walrus Operator
2429

2530
```python
2631
def description(numbers):
@@ -32,22 +37,26 @@ def description(numbers):
3237
return details
3338
```
3439

35-
This reduces the number of lines needed to create variables and improves code readability.
40+
By using the walrus operator, we reduce the need for separate variable declarations while maintaining readability.
3641

37-
## Main Entry Point Example
42+
### Main Entry Point Example
3843

39-
In the main entry point, we create a list of numbers and print their description using the `description` function:
44+
To test the function:
4045

4146
```python
4247
numbers = [110, 5, 200, -4, 7]
4348
print(description(numbers))
4449
```
4550

46-
This will output a dictionary containing the length, sum, and mean of the provided numbers.
51+
**Output:**
52+
53+
```python
54+
{'length': 5, 'sum': 318, 'mean': 63.6}
55+
```
4756

4857
## Checking for Item Existence in a Dictionary
4958

50-
The walrus operator can also be useful for checking the existence of an item in a dictionary and using it immediately. Here's an example:
59+
Another practical use of the walrus operator is checking for and using an item in a dictionary simultaneously:
5160

5261
```python
5362
items = {1: 'cup', 2: 'cha'}
@@ -57,10 +66,20 @@ else:
5766
print('No item found')
5867
```
5968

60-
This example demonstrates how the walrus operator simplifies the code by combining the check and assignment in a single line.
69+
In this example:
70+
- The `items.get(3)` expression checks for the existence of key `3`.
71+
- The walrus operator assigns the result of the check to `item`.
72+
- The code remains concise and avoids duplication of the `items.get(3)` call.
6173

6274
## Controversy and Considerations
6375

64-
It's essential to note that the walrus operator might be considered controversial due to potential readability issues. Some developers find it hard to read, while others see it as a concise way to simplify code. Consider your team's coding standards and prioritize readability when deciding whether to use the walrus operator.
76+
While the walrus operator can make code more concise, it has sparked some controversy among developers. Here are the key points to consider:
77+
78+
1. **Readability**: In some cases, combining assignment and evaluation in a single line can make code harder to read.
79+
2. **Team Standards**: If working in a team, ensure that all members are comfortable with and understand the usage of the walrus operator.
80+
3. **Use Cases**: Reserve the walrus operator for situations where it genuinely enhances code clarity and efficiency.
81+
82+
## Conclusion
83+
84+
The walrus operator is a powerful addition to Python, allowing for more concise and expressive code. However, its usage should prioritize clarity and maintainability. As a developer, consider the context and your audience when deciding whether to use it. With thoughtful application, the walrus operator can be a valuable tool in your Python toolkit.
6585

66-
Remember, the most crucial aspect of coding is to write clear and understandable code. If the walrus operator enhances readability in your specific use case, feel free to leverage it; otherwise, stick to more conventional approaches.data

webpage/docs/python-guide/10_Advanced/03_Lambda_Functions.md

Lines changed: 48 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,37 @@
1+
# Lambda Functions in Python
12

2-
# Lambda Functions
3+
Lambda functions, also known as anonymous functions, are short, concise functions that are often used for one-time operations. This tutorial will introduce you to the basics of lambda functions, their syntax, and their practical applications.
34

4-
Welcome to this tutorial on using lambda functions in Python! In this lesson, we'll explore the basics of lambda functions, how to create them, and how to use them effectively.
5+
## Introduction to Lambda Functions
56

6-
## Introduction to Lambdas
7+
Lambda functions are unnamed functions defined using the `lambda` keyword. They are especially useful for short-lived operations where defining a full function might be unnecessary.
78

8-
Lambdas are nameless functions that you can create on the fly. They are particularly handy for short-lived, one-time-use operations. Let's dive into some code examples.
9+
### Syntax
910

10-
### Simple Lambda
11+
```python
12+
lambda arguments: expression
13+
```
14+
15+
The `lambda` keyword is followed by the arguments, a colon, and the expression that the lambda function will evaluate and return.
16+
17+
## Examples of Lambda Functions
18+
19+
### 1. Simple Lambda
20+
21+
A basic example of a lambda function with a single parameter:
1122

1223
```python
1324
# Single parameter lambda
1425
p = lambda x: print(x)
1526

1627
# Using the lambda
17-
p(10)
18-
p("hello")
28+
p(10) # Output: 10
29+
p("hello") # Output: hello
1930
```
2031

21-
### Lambda with Multiple Parameters
32+
### 2. Lambda with Multiple Parameters
33+
34+
You can define lambdas with multiple parameters:
2235

2336
```python
2437
# Lambda with multiple parameters
@@ -29,7 +42,9 @@ result = add(4, 5)
2942
print(result) # Output: 9
3043
```
3144

32-
### Using Lambdas in a Function
45+
### 3. Using Lambdas in a Function
46+
47+
Lambdas are often passed as arguments to higher-order functions:
3348

3449
```python
3550
from typing import Callable, List
@@ -39,15 +54,17 @@ def use_all(func: Callable, values: List[int]) -> None:
3954
func(value)
4055

4156
# Using the function with a lambda
42-
use_all(lambda x: print(f"{x} times 'x'"))
57+
use_all(lambda x: print(f"{x} times 'x'"), [2, 4, 10])
4358

4459
# Output:
4560
# 2 times 'x'
4661
# 4 times 'x'
4762
# 10 times 'x'
4863
```
4964

50-
### Lambda vs. Regular Function
65+
### 4. Lambda vs. Regular Function
66+
67+
Here’s a comparison between using a lambda function and a regular function:
5168

5269
```python
5370
# Using a lambda
@@ -61,7 +78,11 @@ def multiply_func(x: int) -> None:
6178
use_all(multiply_func, [2, 4, 10])
6279
```
6380

64-
### Sorting with Lambdas
81+
Both approaches yield the same result. Lambdas are more concise, while regular functions are better suited for reuse and readability.
82+
83+
### 5. Sorting with Lambdas
84+
85+
Lambda functions are commonly used as keys for sorting operations:
6586

6687
```python
6788
# Sorting names by length
@@ -72,6 +93,20 @@ print(sorted_names)
7293
# Output: ['Joe', 'Bob', 'Luigi', 'James', 'Samantha']
7394
```
7495

96+
Here, the `key` parameter uses a lambda function to sort the names by their lengths.
97+
98+
## Practical Applications of Lambdas
99+
100+
1. **Functional Programming**: Lambdas are widely used in functional programming constructs like `map()`, `filter()`, and `reduce()`.
101+
2. **Event Handling**: In GUI programming, lambdas are often used to define simple event handlers.
102+
3. **Short-lived Functions**: Lambdas are ideal for operations where defining a standalone function is unnecessary.
103+
104+
## Considerations
105+
106+
- **Readability**: While lambdas are concise, overusing them can make your code harder to understand.
107+
- **Reusability**: Lambdas are limited to single expressions and cannot have multiple statements or annotations, making them less reusable than regular functions.
108+
75109
## Conclusion
76110

77-
Lambdas are powerful tools for concise and expressive coding, especially in scenarios where creating a separate function may be overkill. Consider their readability and reusability when deciding between lambdas and regular functions. Enjoy coding with lambdas!
111+
Lambda functions are a powerful feature in Python, offering a concise way to create short-lived functions. Use them wisely to enhance your code's readability and efficiency. However, for more complex operations, stick to regular functions to ensure clarity and maintainability.
112+

0 commit comments

Comments
 (0)