Skip to content

Commit

Permalink
test deployment
Browse files Browse the repository at this point in the history
  • Loading branch information
CagriCatik committed Jan 22, 2025
1 parent ef8853d commit 036dca8
Show file tree
Hide file tree
Showing 17 changed files with 418 additions and 155 deletions.
73 changes: 52 additions & 21 deletions webpage/docs/python-guide/10_Advanced/01_Mypy.md
Original file line number Diff line number Diff line change
@@ -1,58 +1,89 @@
# Mypy Static Type Checker

# Mypy Static Type Checker

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.
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.

## Installation

To get started with Mypy, install it using the following command:
To start using Mypy, install it via pip:

```bash
pip install mypy
```

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

## Usage in Code Editors
## Enhancing Code Editors

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:
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:

1. Navigate to **Settings**.
2. Go to **Plugins**.
1. Open **Settings**.
2. Navigate to **Plugins**.
3. Search for "Mypy" in the marketplace.
4. Install the plugin (choose the one with more downloads and better ratings).
4. Install the plugin (prefer the one with higher downloads and better ratings).

This plugin provides real-time feedback on type annotations directly within the editor.

## Running Mypy
## Running Mypy from the Command Line

To ensure a thorough check of your code, run Mypy from the command line:
To perform a thorough check of your code, run Mypy via the command line:

```bash
mypy your_script.py
```

This command will identify any type mismatches and provide detailed warnings.
This command analyzes the specified script and reports any type mismatches or errors. It provides detailed warnings to help you fix issues promptly.

## Practical Examples

### Example: List Type Check
### Example 1: List Type Check

Consider a list variable defined to contain strings:
Consider the following example where a list is defined to contain strings:

```python
my_list = ["cup", "apple"]
```

Mypy will catch issues if you attempt to insert incompatible types like booleans or other lists containing integers.
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:

### Example: Optional Arguments
```python
my_list.append(42) # Mypy will flag this as an error
```

Mypy is especially helpful in catching errors related to optional arguments in functions. For instance:
### Example 2: Optional Arguments

Mypy is particularly useful for handling optional arguments in functions. For example:

```python
def my_function(default: int = None):
from typing import Optional

def my_function(default: Optional[int] = None):
# Your function logic here
pass
```

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`.
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.

### Example 3: Type Mismatches in Return Values

Mypy can also validate return types in functions:

```python
from typing import List

def get_items() -> List[str]:
return ["item1", "item2", 42] # Mypy will flag the integer as an error
```

If the return value does not match the specified type, Mypy will raise an error.

## Benefits of Mypy

1. **Enhanced Code Quality**: By ensuring type correctness, Mypy helps reduce bugs and improves maintainability.
2. **Early Error Detection**: Mypy catches type-related issues during development, preventing potential runtime errors.
3. **Improved Readability**: Explicit type annotations make your code easier to understand and maintain.
4. **Seamless Integration**: Mypy integrates with popular code editors and CI/CD pipelines.

## Conclusion

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.
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.

43 changes: 31 additions & 12 deletions webpage/docs/python-guide/10_Advanced/02_Walrus_Operator.md
Original file line number Diff line number Diff line change
@@ -1,11 +1,16 @@
# The Walrus Operator in Python

# Walrus Operator
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.

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.
## Prerequisites

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.

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

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:
The walrus operator can simplify calculations and variable assignments. Here’s a step-by-step example:

### Without the Walrus Operator

```python
def description(numbers):
Expand All @@ -20,7 +25,7 @@ def description(numbers):
return details
```

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

```python
def description(numbers):
Expand All @@ -32,22 +37,26 @@ def description(numbers):
return details
```

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

## Main Entry Point Example
### Main Entry Point Example

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

```python
numbers = [110, 5, 200, -4, 7]
print(description(numbers))
```

This will output a dictionary containing the length, sum, and mean of the provided numbers.
**Output:**

```python
{'length': 5, 'sum': 318, 'mean': 63.6}
```

## Checking for Item Existence in a Dictionary

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:
Another practical use of the walrus operator is checking for and using an item in a dictionary simultaneously:

```python
items = {1: 'cup', 2: 'cha'}
Expand All @@ -57,10 +66,20 @@ else:
print('No item found')
```

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

## Controversy and Considerations

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.
While the walrus operator can make code more concise, it has sparked some controversy among developers. Here are the key points to consider:

1. **Readability**: In some cases, combining assignment and evaluation in a single line can make code harder to read.
2. **Team Standards**: If working in a team, ensure that all members are comfortable with and understand the usage of the walrus operator.
3. **Use Cases**: Reserve the walrus operator for situations where it genuinely enhances code clarity and efficiency.

## Conclusion

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.

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
61 changes: 48 additions & 13 deletions webpage/docs/python-guide/10_Advanced/03_Lambda_Functions.md
Original file line number Diff line number Diff line change
@@ -1,24 +1,37 @@
# Lambda Functions in Python

# Lambda Functions
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.

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.
## Introduction to Lambda Functions

## Introduction to Lambdas
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.

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.
### Syntax

### Simple Lambda
```python
lambda arguments: expression
```

The `lambda` keyword is followed by the arguments, a colon, and the expression that the lambda function will evaluate and return.

## Examples of Lambda Functions

### 1. Simple Lambda

A basic example of a lambda function with a single parameter:

```python
# Single parameter lambda
p = lambda x: print(x)

# Using the lambda
p(10)
p("hello")
p(10) # Output: 10
p("hello") # Output: hello
```

### Lambda with Multiple Parameters
### 2. Lambda with Multiple Parameters

You can define lambdas with multiple parameters:

```python
# Lambda with multiple parameters
Expand All @@ -29,7 +42,9 @@ result = add(4, 5)
print(result) # Output: 9
```

### Using Lambdas in a Function
### 3. Using Lambdas in a Function

Lambdas are often passed as arguments to higher-order functions:

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

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

# Output:
# 2 times 'x'
# 4 times 'x'
# 10 times 'x'
```

### Lambda vs. Regular Function
### 4. Lambda vs. Regular Function

Here’s a comparison between using a lambda function and a regular function:

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

### Sorting with Lambdas
Both approaches yield the same result. Lambdas are more concise, while regular functions are better suited for reuse and readability.

### 5. Sorting with Lambdas

Lambda functions are commonly used as keys for sorting operations:

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

Here, the `key` parameter uses a lambda function to sort the names by their lengths.

## Practical Applications of Lambdas

1. **Functional Programming**: Lambdas are widely used in functional programming constructs like `map()`, `filter()`, and `reduce()`.
2. **Event Handling**: In GUI programming, lambdas are often used to define simple event handlers.
3. **Short-lived Functions**: Lambdas are ideal for operations where defining a standalone function is unnecessary.

## Considerations

- **Readability**: While lambdas are concise, overusing them can make your code harder to understand.
- **Reusability**: Lambdas are limited to single expressions and cannot have multiple statements or annotations, making them less reusable than regular functions.

## Conclusion

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!
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.

Loading

0 comments on commit 036dca8

Please sign in to comment.