Skip to content

Improving Examples #492

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Apr 17, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
354 changes: 177 additions & 177 deletions coverage.xml

Large diffs are not rendered by default.

47 changes: 41 additions & 6 deletions docs/examples/cal_example.md
Original file line number Diff line number Diff line change
Expand Up @@ -77,9 +77,13 @@ This module is licensed under the MIT License.

```python
from dsg_lib.common_functions import calendar_functions
from typing import List, Any

month_list: list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
month_names: list = [
# List of month numbers to test, including invalid values (0, 13)
month_list: List[int] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]

# List of month names to test, including an invalid value ("bob")
month_names: List[str] = [
"january",
"february",
"march",
Expand All @@ -95,20 +99,51 @@ month_names: list = [
"bob",
]


def calendar_check_number():
def calendar_check_number() -> None:
"""
Example: Demonstrates converting month numbers to month names.
Iterates through `month_list` and prints the result of get_month for each.
"""
for i in month_list:
month = calendar_functions.get_month(month=i)
print(month)


def calendar_check_name():
def calendar_check_name() -> None:
"""
Example: Demonstrates converting month names to month numbers.
Iterates through `month_names` and prints the result of get_month_number for each.
"""
for i in month_names:
month = calendar_functions.get_month_number(month_name=i)
print(month)

def calendar_check_float_and_invalid_types() -> None:
"""
Example: Tests get_month with float values and various invalid types.
Shows how the function handles non-integer and unexpected input types.
"""
print("\nTesting get_month with float and invalid types:")
test_values: List[Any] = [1.0, 12.0, 5.5, "3", None, [1], {"month": 2}]
for val in test_values:
print(f"Input: {val!r} -> Output: {calendar_functions.get_month(month=val)}")

def calendar_check_name_variants() -> None:
"""
Example: Tests get_month_number with name variants and invalid types.
Includes extra spaces, different cases, abbreviations, and non-string types.
"""
print("\nTesting get_month_number with name variants and invalid types:")
test_names: List[Any] = [
" January ", "FEBRUARY", "mar", "Apr", "may", "JUNE", "July", "august", "Sept", "oct", "nov", "december",
5, None, ["March"], {"month": "April"}
]
for name in test_names:
print(f"Input: {name!r} -> Output: {calendar_functions.get_month_number(month_name=name)}")

if __name__ == "__main__":
# Run all example checks to demonstrate library usage and edge case handling
calendar_check_number()
calendar_check_name()
calendar_check_float_and_invalid_types()
calendar_check_name_variants()
```
121 changes: 95 additions & 26 deletions docs/examples/csv_example.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

# CSV Example Module

This module provides examples of how to work with CSV files using the `dsg_lib` library. It includes functions for saving data to a CSV file, opening and reading data from a CSV file, and creating sample files for testing purposes. The module is designed to demonstrate the usage of the `file_functions` and `logging_config` utilities provided by `dsg_lib`.
This module provides examples of how to work with CSV files using the `dsg_lib` library. It includes functions for saving data to a CSV file, opening and reading data from a CSV file, appending data to an existing CSV file, deleting a CSV file, and creating sample files for testing purposes. The module is designed to demonstrate the usage of the `file_functions` and `logging_config` utilities provided by `dsg_lib`.

## Functions

Expand All @@ -27,6 +27,18 @@ Opens a CSV file and returns its contents as a dictionary. This function assumes
- Additional options such as delimiter, quote level, and space handling can be configured.
- Refer to the Python CSV documentation for more details: [Python CSV Documentation](https://docs.python.org/3/library/csv.html).

### `append_some_data(rows: list)`
Appends rows to an existing CSV file. The function uses the `append_csv` utility from `dsg_lib`.

- **Parameters**:
- `rows` (list): A list of lists containing the rows to append. The header must match the existing file.

### `delete_example_file(file_name: str)`
Deletes a CSV file. The function uses the `delete_file` utility from `dsg_lib`.

- **Parameters**:
- `file_name` (str): The name of the file to delete.

### `sample_files()`
Creates sample files for testing purposes. This function uses the `create_sample_files` utility from `dsg_lib`.

Expand All @@ -42,7 +54,18 @@ if __name__ == "__main__":

# Open and read data from a CSV file
opened_file = open_some_data("your-file-name.csv")
print(opened_file)
print("Opened CSV data:", opened_file)

# Append data to an existing CSV file
rows_to_append = [
["thing_one", "thing_two"], # header row (must match)
["i", "j"],
["k", "l"],
]
append_some_data(rows_to_append)

# Delete the CSV file
delete_example_file("your-file-name.csv")

# Create sample files for testing
sample_files()
Expand All @@ -56,11 +79,8 @@ The module configures logging using the `config_log` utility from `dsg_lib`. The
This module is licensed under the MIT License.

```python
from dsg_lib.common_functions.file_functions import (
create_sample_files,
open_csv,
save_csv,
)
from typing import List, Dict, Any
from dsg_lib.common_functions.file_functions import create_sample_files, open_csv, save_csv
from dsg_lib.common_functions.logging_config import config_log

config_log(logging_level="DEBUG")
Expand All @@ -74,9 +94,14 @@ example_list = [
]


def save_some_data(example_list: list):
# function requires file_name and data list to be sent.
# see documentation for additonal information
def save_some_data(example_list: List[List[str]]) -> None:
"""
Save a list of lists to a CSV file using dsg_lib's save_csv.

Args:
example_list (List[List[str]]): Data to save, including header as first row.
"""
# Save data to CSV with custom delimiter and quote character
save_csv(
file_name="your-file-name.csv",
data=example_list,
Expand All @@ -86,32 +111,76 @@ def save_some_data(example_list: list):
)


def open_some_data(the_file_name: str) -> dict:
"""
function requires file_name and a dictionary will be returned
this function is designed with the idea that the CSV file has a header row.
see documentation for additonal information
options
file_name: str | "myfile.csv"
delimit: str | example - ":" single character only inside quotes
quote_level:str | ["none","non-numeric","minimal","all"] default is minimal
skip_initial_space:bool | default is True
See Python documentation as needed https://docs.python.org/3/library/csv.html
def open_some_data(the_file_name: str) -> List[Dict[str, Any]]:
"""
Open a CSV file and return its contents as a list of dictionaries.

Args:
the_file_name (str): Name of the CSV file to open.

result: dict = open_csv(file_name=the_file_name)
Returns:
List[Dict[str, Any]]: List of rows as dictionaries.
"""
result = open_csv(file_name=the_file_name)
return result


def sample_files():
def append_some_data(rows: List[List[str]]) -> None:
"""
Append rows to an existing CSV file.

Args:
rows (List[List[str]]): Rows to append, header must match existing file.
"""
from dsg_lib.common_functions.file_functions import append_csv
append_csv(
file_name="your-file-name.csv",
data=rows,
root_folder="/data",
delimiter="|",
quotechar='"',
)


def delete_example_file(file_name: str) -> None:
"""
Delete a CSV file using dsg_lib's delete_file.

Args:
file_name (str): Name of the file to delete.
"""
from dsg_lib.common_functions.file_functions import delete_file
delete_file(file_name)


def sample_files() -> None:
"""
Create sample files for testing.
"""
filename = "test_sample"
samplesize = 1000
create_sample_files(filename, samplesize)


if __name__ == "__main__":
# save_some_data(example_list)
# opened_file: dict = open_some_data("your-file-name.csv")
# print(opened_file)
# Example: Save data to CSV
save_some_data(example_list)

# Example: Open and read data from CSV
opened_file = open_some_data("your-file-name.csv")
print("Opened CSV data:", opened_file)

# Example: Append data to CSV (header must match)
rows_to_append = [
["thing_one", "thing_two"], # header row (must match)
["i", "j"],
["k", "l"],
]
append_some_data(rows_to_append)

# Example: Delete the CSV file
delete_example_file("your-file-name.csv")

# Example: Create sample files
sample_files()
```
3 changes: 2 additions & 1 deletion docs/examples/csv_example_with_timer.md
Original file line number Diff line number Diff line change
Expand Up @@ -51,11 +51,12 @@ The script will continuously generate and save CSV files until manually stopped.
This module is licensed under the MIT License.

```python
import random
import time
from datetime import datetime

from dsg_lib.common_functions.file_functions import save_csv
from dsg_lib.common_functions.logging_config import config_log
import random

config_log(logging_level="DEBUG")

Expand Down
Loading
Loading