Skip to content

API Reference

Auto-generated code documentation.

analytics_project

demo_module_basics

Demonstrate Python basics for professional analytics.

This module demonstrates fundamental Python concepts essential for data analysts, including imports, variables, functions, and function calls.

Module Information
  • Filename: demo_module_basics.py
  • Module: demo_module_basics
  • Location: src/analytics_project/
Key Concepts
  • Module imports and code organization
  • Variable declaration and scope
  • Function definition (reusable logic)
  • Function invocation and returns
Professional Applications
  • Building maintainable analytics pipelines
  • Creating reusable analysis functions
  • Organizing code for team collaboration
  • Setting up logging for production debugging

demo_basics

demo_basics() -> None

Demonstrate Python basics.

Source code in src/analytics_project/demo_module_basics.py
88
89
90
91
92
93
94
95
96
97
def demo_basics() -> None:
    """Demonstrate Python basics."""
    logger.info("Starting demo_python() function.")
    show_naming_and_comments()
    show_variables_and_types()
    show_functions_and_fstrings()
    show_builtins_example()
    show_truths()
    logger.info("Experiment with this demo script to learn the basics quickly.")
    logger.info("Exiting demo_python() function.")

main

main() -> None

Test demo locally.

Source code in src/analytics_project/demo_module_basics.py
105
106
107
108
109
110
111
def main() -> None:
    """Test demo locally."""
    try:
        init_logger()
    except Exception as exc:
        logger.exception(f"Exception occurred during logger initialization: {exc}")
    demo_basics()

demo_module_languages

Demonstrate international features.

This module showcases Python's strengths for global analytics projects, including advanced language features and character encoding.

Module Information
  • Filename: demo_module_languages.py
  • Module: demo_module_languages
  • Location: src/analytics_project/
Professional Applications
  • Multi-language data processing
  • Accessible analytics dashboards
  • International team collaboration
  • Voice-enabled reporting systems

demo_greetings

demo_greetings() -> None

Greet the user in multiple languages.

Source code in src/analytics_project/demo_module_languages.py
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
def demo_greetings() -> None:
    """Greet the user in multiple languages."""
    greetings = [
        "English: Hello! Welcome to Python programming.",
        "Spanish: Hola! Bienvenido a la programación en Python.",
        "Mandarin: 你好! 欢迎学习Python编程.",
        "French:  Bonjour! Bienvenue à la programmation Python.",
        "German:  Hallo! Willkommen bei der Python-Programmierung.",
        "Telugu:  హలో! Python ప్రోగ్రామింగ్‌లోకి స్వాగతం.",
        "Norwegian: Hei! Velkommen til Python-programmering.",
    ]

    # Join all greetings into one multiline string
    all_greetings = "\n".join(greetings)

    logger.info(f"\nGreetings Professional Analyst:\n{all_greetings}")

main

main() -> None

Run the languages demo.

Source code in src/analytics_project/demo_module_languages.py
53
54
55
56
57
58
59
def main() -> None:
    """Run the languages demo."""
    try:
        init_logger()
    except Exception as exc:
        logger.exception(f"Exception occurred during logger initialization: {exc}")
    demo_greetings()

demo_module_stats

Demonstrate statistical calculations for professional analytics.

This module showcases Python's statistical capabilities using both built-in functions and the statistics library for common data analysis tasks.

Module Information
  • Filename: demo_module_stats.py
  • Module: demo_module_stats
  • Location: src/analytics_project/
Key Concepts
  • Type hints for function parameters and returns
  • Statistical functions (min, max, mean, stdev)
  • Formatted output for professional reporting
  • Logging statistical summaries
Professional Applications
  • Data quality assessment
  • Performance metrics analysis
  • Risk calculations
  • A/B testing results

calculate_max

calculate_max(scores: Sequence[float]) -> float

Return the maximum value in the list.

Source code in src/analytics_project/demo_module_stats.py
44
45
46
def calculate_max(scores: Sequence[float]) -> float:
    """Return the maximum value in the list."""
    return max(scores)

calculate_mean

calculate_mean(scores: Sequence[float]) -> float

Return the mean (average) of the list.

Source code in src/analytics_project/demo_module_stats.py
49
50
51
def calculate_mean(scores: Sequence[float]) -> float:
    """Return the mean (average) of the list."""
    return statistics.mean(scores)

calculate_min

calculate_min(scores: Sequence[float]) -> float

Return the minimum value in the list.

Source code in src/analytics_project/demo_module_stats.py
39
40
41
def calculate_min(scores: Sequence[float]) -> float:
    """Return the minimum value in the list."""
    return min(scores)

calculate_standard_deviation

calculate_standard_deviation(
    scores: Sequence[float],
) -> float

Return the standard deviation of the list.

Source code in src/analytics_project/demo_module_stats.py
54
55
56
def calculate_standard_deviation(scores: Sequence[float]) -> float:
    """Return the standard deviation of the list."""
    return statistics.stdev(scores)

demo_stats

demo_stats(scores: Sequence[float] | None = None) -> None

Demonstrate how to calculate and log statistics for a list of numbers.

Parameters:

Name Type Description Default
scores Sequence[float] | None

Optional list or tuple of numeric values. If not provided, uses a default list.

None
Source code in src/analytics_project/demo_module_stats.py
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
def demo_stats(scores: Sequence[float] | None = None) -> None:
    """Demonstrate how to calculate and log statistics for a list of numbers.

    Args:
        scores: Optional list or tuple of numeric values.
                If not provided, uses a default list.
    """
    if scores is None:
        scores = [3.5, 4.0, 4.8, 2.9, 3.7, 4.3, 3.8]

    n = len(scores)
    v_min = calculate_min(scores)
    v_max = calculate_max(scores)
    v_mean = calculate_mean(scores)
    v_std = calculate_standard_deviation(scores)

    # One clean block: easy to scan in terminal and log file.
    # Use v_ prefix to indicate "value of" each metric.
    # So we don't conflict with built-in function names like min() and max().
    # Use formatted strings (f-strings) for alignment and decimal places.
    # Notice the f just before the opening quote of the string.
    # That lets us embed variables directly in the string.
    summary = (
        "STATS SUMMARY\n"
        f"Scores (n={n}): {scores}\n"
        f"{'metric':<18}{'value':>10}\n"
        f"{'-' * 28}\n"
        f"{'min':<18}{v_min:>10.2f}\n"
        f"{'max':<18}{v_max:>10.2f}\n"
        f"{'mean':<18}{v_mean:>10.2f}\n"
        f"{'stdev':<18}{v_std:>10.2f}\n"
    )

    # Log the summary in one block - \n means `new line` and leaves a blank line
    logger.info("\n" + summary)

main

main() -> None

Run demo_stats() locally for testing.

Source code in src/analytics_project/demo_module_stats.py
106
107
108
109
110
111
112
113
def main() -> None:
    """Run demo_stats() locally for testing."""
    try:
        init_logger()
    except Exception as exc:
        logger.exception(f"Exception occurred during logger initialization: {exc}")

    demo_stats()

demo_module_viz

Demonstrate data visualization for professional analytics.

This module demonstrates Python's data visualization capabilities using Seaborn and Matplotlib to create publication-quality charts for communicating analytical insights.

Module Information
  • Filename: demo_module_viz.py
  • Module: demo_module_viz
  • Location: src/analytics_project/
Key Concepts
  • Statistical data visualization with Seaborn
  • Working with built-in datasets
  • Creating publication-quality figures
  • Customizing plots for clarity and impact
Professional Applications
  • Executive dashboards
  • Research publications
  • Client presentations
  • Exploratory data analysis

demo_viz

demo_viz() -> None

Create and display a scatter plot of penguin data.

Source code in src/analytics_project/demo_module_viz.py
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
def demo_viz() -> None:
    """Create and display a scatter plot of penguin data."""
    try:
        # Load the Penguins dataset
        data = sns.load_dataset("penguins")
        logger.info("Loaded Penguins dataset successfully.")

        # Create a scatter plot
        sns.scatterplot(data=data, x="bill_length_mm", y="bill_depth_mm", hue="species")
        plt.title("Penguin Bill Dimensions by Species")
        plt.xlabel("Bill Length (mm)")
        plt.ylabel("Bill Depth (mm)")

        logger.info("Displaying chart... Close the window to exit.")
        plt.show()
        logger.info("Chart closed successfully.")

    except Exception as e:
        logger.error(f"Error creating or displaying chart: {e}")

main

main() -> None

Run chart demo locally with its own logger if needed.

Source code in src/analytics_project/demo_module_viz.py
65
66
67
68
69
70
71
72
def main() -> None:
    """Run chart demo locally with its own logger if needed."""
    try:
        init_logger()
    except Exception as exc:
        logger.exception(f"Exception occurred during logger initialization: {exc}")

    demo_viz()

main

Entry point for professional analytics project execution.

This module serves as the orchestrator, demonstrating how professional Python projects integrate multiple modules into a cohesive application.

Module Information
  • Filename: main.py
  • Module: main
  • Location: src/analytics_project/
Key Concepts
  • Module orchestration and integration
  • Sequential workflow execution
  • Error handling at the application level
  • Project structure best practices
Professional Applications
  • ETL pipeline coordination
  • Automated reporting workflows
  • Batch processing systems
  • Scheduled analytics jobs

main

main() -> int

Demonstrate a complete Python project structure.

This function coordinates multiple demo modules to illustrate how professional Python projects integrate and run as a pipeline.

Returns:

Name Type Description
int int

Exit status code (0 for success, 1 for failure) — standard practice in professional Python projects.

Source code in src/analytics_project/main.py
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
def main() -> int:
    """Demonstrate a complete Python project structure.

    This function coordinates multiple demo modules to illustrate
    how professional Python projects integrate and run as a pipeline.

    Returns:
        int: Exit status code (0 for success, 1 for failure)
             — standard practice in professional Python projects.
    """
    # Initialize logging for consistent console + file output
    init_logger()
    logger.info("Starting main analytics pipeline.")

    try:
        # Sequentially run each module to simulate an ETL-like process
        demo_basics()  # Basic operations and data handling
        demo_stats()  # Compute and log statistical metrics
        demo_viz()  # Generate example visualizations
        demo_greetings()  # Simple language demo (text output)

        logger.info("Demo pipeline complete.")
        return 0  # Returning 0 indicates success in professional scripts

    except Exception as e:
        # Application-level exception handling (never let a crash go silent)
        logger.error(f"Error executing demo pipeline: {e}")
        return 1  # Non-zero exit codes signal an error to the OS or CI system

utils_logger

Provide centralized logging for professional analytics projects.

This module configures project-wide logging to track events, debug issues, and maintain audit trails during data analysis workflows.

Module Information
  • Filename: utils_logger.py
  • Module: utils_logger
  • Location: src/analytics_project/
Key Concepts
  • Centralized logging configuration
  • Log levels (DEBUG, INFO, WARNING, ERROR)
  • File-based log persistence
  • Colorized console output with Loguru
Professional Applications
  • Production debugging and troubleshooting
  • Audit trails for regulatory compliance
  • Performance monitoring and optimization
  • Error tracking in data pipelines

get_log_file_path

get_log_file_path() -> pathlib.Path

Return the path to the active log file, or default path if not initialized.

Source code in src/analytics_project/utils_logger.py
48
49
50
51
52
53
def get_log_file_path() -> pathlib.Path:
    """Return the path to the active log file, or default path if not initialized."""
    if _log_file_path is not None:
        return _log_file_path
    # Fallback: predictable location even before init_logger() runs
    return project_root / "project.log"

init_logger

init_logger(
    level: str = 'INFO',
    *,
    log_dir: str | Path = project_root,
    log_file_name: str = 'project.log',
) -> pathlib.Path

Initialize the logger and return the log file path.

Ensures the log folder exists and configures logging to write to a file.

Parameters:

Name Type Description Default
level str

Logging level (e.g., "INFO", "DEBUG").

'INFO'
log_dir str | Path

Directory where the log file will be written.

project_root
log_file_name str

File name for the log file.

'project.log'

Returns:

Type Description
Path

pathlib.Path: The resolved path to the log file.

Source code in src/analytics_project/utils_logger.py
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
def init_logger(
    level: str = "INFO",
    *,
    log_dir: str | pathlib.Path = project_root,
    log_file_name: str = "project.log",
) -> pathlib.Path:
    """Initialize the logger and return the log file path.

    Ensures the log folder exists and configures logging to write to a file.

    Args:
        level (str): Logging level (e.g., "INFO", "DEBUG").
        log_dir: Directory where the log file will be written.
        log_file_name: File name for the log file.

    Returns:
        pathlib.Path: The resolved path to the log file.
    """
    global _is_configured
    if _is_configured:
        # If already configured once for this process
        return pathlib.Path(log_dir) / log_file_name

    # print a visual separator before logs
    print("-----------------------")

    # Resolve and ensure log folder exists
    log_folder = pathlib.Path(log_dir).expanduser().resolve()
    log_folder.mkdir(parents=True, exist_ok=True)

    # Build log file path
    log_file = log_folder / log_file_name

    try:
        fmt = "{time:YYYY-MM-DD HH:mm}:{level:<7} AT {file}:{line}: {message}"
        # Remove any existing Loguru handlers to avoid duplicate output
        logger.remove()
        logger.add(sys.stderr, level=level, format=fmt)
        logger.add(
            log_file,
            level=level,
            enqueue=True,
            backtrace=True,
            diagnose=False,
            rotation="10 MB",
            retention="7 days",
            encoding="utf-8",
            format=fmt,
        )
        logger.info(f"Logging to file: {log_file.resolve()}")
        _is_configured = True
        _log_file_path = log_file  # cache for retrieval
    except Exception as e:
        logger.error(f"Error configuring logger to write to file: {e}")

    return log_file

log_example

log_example() -> None

Demonstrate logging behavior with example messages.

Source code in src/analytics_project/utils_logger.py
114
115
116
117
118
def log_example() -> None:
    """Demonstrate logging behavior with example messages."""
    logger.info("This is an example info message.")
    logger.warning("This is an example warning message.")
    logger.error("This is an example error message.")

main

main() -> None

Execute logger setup and demonstrate its usage.

Source code in src/analytics_project/utils_logger.py
121
122
123
124
125
def main() -> None:
    """Execute logger setup and demonstrate its usage."""
    log_file = init_logger()
    log_example()
    logger.info(f"View the log output at {log_file}")