Skip to content

Development#22

Merged
gjbex merged 12 commits intomasterfrom
development
Mar 25, 2026
Merged

Development#22
gjbex merged 12 commits intomasterfrom
development

Conversation

@gjbex
Copy link
Copy Markdown
Owner

@gjbex gjbex commented Mar 25, 2026

Summary by Sourcery

Document and demonstrate additional concepts in notebooks and docs, including default values in Pydantic models and decorator arguments with bounds checking, alongside minor formatting and configuration improvements.

New Features:

  • Add a Pydantic notebook section illustrating default values and default_factory behavior.
  • Introduce a decorator example that accepts arguments to enforce value bounds on a function parameter.

Enhancements:

  • Reformat dynamic class creation examples for readability in the object-orientation notebook.
  • Update object-oriented vs functional notebook text, benchmark outputs, and Python version metadata across several notebooks.
  • Clarify hardware and environment requirements for hands-on participation in the documentation README.
  • Document the new decorator-with-arguments example in the decorators README.
  • Set a title in the docs site configuration.

@review-notebook-app
Copy link
Copy Markdown

Check out this pull request on  ReviewNB

See visual diffs & provide feedback on Jupyter Notebooks.


Powered by ReviewNB

@sourcery-ai
Copy link
Copy Markdown

sourcery-ai Bot commented Mar 25, 2026

Reviewer's Guide

Adds a new parameterized decorator example and associated documentation, introduces a Pydantic default-values section, improves formatting and outputs in several notebooks, and updates documentation metadata (site title and environment requirements).

Sequence diagram for the new parameterized decorator call flow

sequenceDiagram
    actor User
    participant silly as silly_decorated
    participant wrapper as wrapper
    participant silly_orig as silly_original

    User->>silly: call silly(0.5)
    activate silly
    silly->>wrapper: delegate call(0.5)
    deactivate silly
    activate wrapper
    wrapper->>wrapper: check min_value <= x <= max_value
    alt x within bounds
        wrapper->>silly_orig: call x**2 - 2.0
        activate silly_orig
        silly_orig-->>wrapper: result
        deactivate silly_orig
        wrapper-->>User: result
    else x out of bounds
        wrapper-->>User: raise ValueError
    end
    deactivate wrapper
Loading

Class diagram for new decorator and Pydantic Agent model

classDiagram
    class BaseModel
    class Field

    class Agent {
        +str name
        +bool interactive = False
        +list~str~ tools = Field(default_factory=list)
    }

    BaseModel <|-- Agent

    class DecoratorsModule {
        +check_bounds(min_value, max_value) check_bounds_wrapper
        +check_bounds_wrapper(_func) wrapper
        +wrapper(x) float
        +silly(x) float
    }

    class CheckBoundsClosure {
        +float min_value
        +float max_value
        +check_bounds_wrapper(_func) wrapper
    }

    class WrapperFunction {
        +float min_value
        +float max_value
        +wrapper(x) float
    }

    DecoratorsModule o-- CheckBoundsClosure
    CheckBoundsClosure o-- WrapperFunction
    DecoratorsModule ..> Agent : independent example
    DecoratorsModule ..> BaseModel : no direct dependency
Loading

File-Level Changes

Change Details Files
Introduce a parameterized decorator example that validates argument bounds and document it in the decorators README.
  • Add check_bounds decorator factory that returns a wrapper verifying a single positional argument x lies between configurable min and max values, raising ValueError when out of bounds.
  • Define silly(x) function decorated with @check_bounds to demonstrate usage and return a simple quadratic expression.
  • Provide a main block that exercises silly with an in-bounds value and handles the expected ValueError for an out-of-bounds value, printing messages to stdout.
  • Extend decorators README to describe the new decorator_arguments.py example and explain its check_range-style behavior.
source-code/decorators/decorator_arguments.py
source-code/decorators/README.md
Enhance teaching notebooks with new Pydantic content, reformat dynamic class definitions, and refresh outputs/metadata.
  • Add a "Default values" section to the Pydantic notebook with markdown explanation and code cells demonstrating BaseModel default values and Field(default_factory=list) semantics across multiple instances.
  • Reformat dynamic class/dataclass construction in the dynamic_classes notebook to multi-line, more readable style for Cat, Dog, Animal, and Cat via type().
  • Update oo_vs_functional notebook docstring section headers from generic 'Params' to NumPy-style 'Parameters' and adjust the example block spacing; refresh performance benchmark outputs, median-calculation example prints, and one matplotlib figure output, along with a few result tuples and execution counts.
  • Normalize Python metadata (version fields) across several notebooks (pydantic, oo_vs_functional, dynamic_classes, prime_time) to 3.12.3 without altering core logic or exercises.
source-code/pydantic.ipynb
source-code/oo_vs_functional.ipynb
source-code/object-orientation/dynamic_classes.ipynb
source-code/prime_time.ipynb
Update documentation to clarify hands-on requirements and configure the docs site title.
  • Add a short section to the main docs README describing prerequisites for following along hands-on (internet-connected machine, Jupyter Lab-capable Python environment, or Google Colab access).
  • Set the docs _config.yml title to "Python software development" for the Jekyll-based site.
docs/README.md
docs/_config.yml

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

Copy link
Copy Markdown

@sourcery-ai sourcery-ai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey - I've found 2 issues, and left some high level feedback:

  • In decorator_arguments.py, the wrapper currently only accepts a single positional argument x; if you intend this decorator to be reusable, consider changing the signature to wrapper(*args, **kwargs) and extracting the value to check, so it works with functions that take multiple or keyword arguments while preserving call semantics.
  • The error handling in decorator_arguments.py uses e.message, which is not a standard attribute on ValueError in modern Python; use str(e) (or repr(e)) in the f-string instead to ensure the exception message is printed correctly.
  • The new README entry under source-code/decorators/README.md refers to a check_range decorator, but the implementation is named check_bounds; aligning the names will avoid confusion for readers looking for the example.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- In `decorator_arguments.py`, the `wrapper` currently only accepts a single positional argument `x`; if you intend this decorator to be reusable, consider changing the signature to `wrapper(*args, **kwargs)` and extracting the value to check, so it works with functions that take multiple or keyword arguments while preserving call semantics.
- The error handling in `decorator_arguments.py` uses `e.message`, which is not a standard attribute on `ValueError` in modern Python; use `str(e)` (or `repr(e)`) in the f-string instead to ensure the exception message is printed correctly.
- The new README entry under `source-code/decorators/README.md` refers to a `check_range` decorator, but the implementation is named `check_bounds`; aligning the names will avoid confusion for readers looking for the example.

## Individual Comments

### Comment 1
<location path="source-code/decorators/decorator_arguments.py" line_range="20-28" />
<code_context>
+    '''
+    def check_bounds_wrapper(_func):
+        @functools.wraps(_func)
+        def wrapper(x):
+            if min_value > x or x > max_value:
+                raise ValueError(f'argument {x} not in [{min_value}, {max_value}]')
+            return _func(x)
</code_context>
<issue_to_address>
**suggestion:** Decorator only supports a single positional argument; consider generalizing to *args/**kwargs or making this constraint explicit.

Currently `check_bounds` will throw a generic `TypeError` if used on a function with more than one argument, because `wrapper` only accepts `x`. To make this safer, you could define `wrapper(*args, **kwargs)`, forward all arguments to `_func`, and explicitly check the relevant argument (e.g., `args[0]`). If the decorator is intentionally limited to single-argument functions, consider validating `_func`’s signature up front so incorrect usage fails with a clear error message.

```suggestion
    '''
    def check_bounds_wrapper(_func):
        @functools.wraps(_func)
        def wrapper(*args, **kwargs):
            if not args:
                raise TypeError(
                    "check_bounds-decorated functions must have at least one "
                    "positional argument to check"
                )
            x = args[0]
            if min_value > x or x > max_value:
                raise ValueError(f'argument {x} not in [{min_value}, {max_value}]')
            return _func(*args, **kwargs)
        return wrapper
    return check_bounds_wrapper
```
</issue_to_address>

### Comment 2
<location path="source-code/decorators/decorator_arguments.py" line_range="51-53" />
<code_context>
+if __name__ == '__main__':
+    print(silly(0.5))
+    try:
+        print(silly(2.5))
+    except ValueError as e:
+        print(f'Excepton raised as expected: {e.message}')
</code_context>
<issue_to_address>
**issue (bug_risk):** Catching ValueError and using `e.message` will fail; use `str(e)` (and fix the typo) instead.

In Python 3, `ValueError` instances don’t have a `.message` attribute, so `e.message` will raise an `AttributeError` instead of showing the original error. Use `str(e)` or interpolate `e` directly, e.g.:

```python
except ValueError as e:
    print(f"Exception raised as expected: {e}")
```

Also, fix the typo: `Excepton``Exception`.
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

Comment on lines +20 to +28
'''
def check_bounds_wrapper(_func):
@functools.wraps(_func)
def wrapper(x):
if min_value > x or x > max_value:
raise ValueError(f'argument {x} not in [{min_value}, {max_value}]')
return _func(x)
return wrapper
return check_bounds_wrapper
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion: Decorator only supports a single positional argument; consider generalizing to *args/**kwargs or making this constraint explicit.

Currently check_bounds will throw a generic TypeError if used on a function with more than one argument, because wrapper only accepts x. To make this safer, you could define wrapper(*args, **kwargs), forward all arguments to _func, and explicitly check the relevant argument (e.g., args[0]). If the decorator is intentionally limited to single-argument functions, consider validating _func’s signature up front so incorrect usage fails with a clear error message.

Suggested change
'''
def check_bounds_wrapper(_func):
@functools.wraps(_func)
def wrapper(x):
if min_value > x or x > max_value:
raise ValueError(f'argument {x} not in [{min_value}, {max_value}]')
return _func(x)
return wrapper
return check_bounds_wrapper
'''
def check_bounds_wrapper(_func):
@functools.wraps(_func)
def wrapper(*args, **kwargs):
if not args:
raise TypeError(
"check_bounds-decorated functions must have at least one "
"positional argument to check"
)
x = args[0]
if min_value > x or x > max_value:
raise ValueError(f'argument {x} not in [{min_value}, {max_value}]')
return _func(*args, **kwargs)
return wrapper
return check_bounds_wrapper

Comment thread source-code/decorators/decorator_arguments.py Outdated
@gjbex gjbex merged commit eb93f88 into master Mar 25, 2026
1 check passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant