Skip to content

Commit 26f8630

Browse files
committed
Working on system automation since scripts move. updated files and generated docs.
1 parent 677f63c commit 26f8630

File tree

71 files changed

+3192
-1481
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

71 files changed

+3192
-1481
lines changed
Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
---
2+
file: behavioral/chain_of_responsibility.py
3+
chunk: behavioral_chain_of_responsibility.md
4+
---
5+
6+
```python
7+
"""
8+
Behavioral Pattern: Chain of Responsibility
9+
10+
Lets you pass requests along a chain of handlers, where each handler decides
11+
whether to process the request or pass it along.
12+
Promotes loose coupling between sender and receiver.
13+
"""
14+
15+
from __future__ import annotations
16+
from abc import ABC, abstractmethod
17+
from typing import Optional
18+
19+
class Handler(ABC):
20+
"""Base Handler class with chaining support."""
21+
22+
_next_handler: Optional[Handler] = None
23+
24+
def set_next(self, handler: Handler) -> Handler:
25+
self._next_handler = handler
26+
return handler
27+
28+
@abstractmethod
29+
def handle(self, request: str) -> Optional[str]:
30+
pass
31+
32+
class MonkeyHandler(Handler):
33+
def handle(self, request: str) -> Optional[str]:
34+
if request == "Banana":
35+
return "Monkey: I'll eat the Banana."
36+
elif self._next_handler:
37+
return self._next_handler.handle(request)
38+
return None
39+
40+
class SquirrelHandler(Handler):
41+
def handle(self, request: str) -> Optional[str]:
42+
if request == "Nut":
43+
return "Squirrel: I'll eat the Nut."
44+
elif self._next_handler:
45+
return self._next_handler.handle(request)
46+
return None
47+
48+
class DogHandler(Handler):
49+
def handle(self, request: str) -> Optional[str]:
50+
if request == "Meat":
51+
return "Dog: I'll eat the Meat."
52+
elif self._next_handler:
53+
return self._next_handler.handle(request)
54+
return None
55+
56+
# Example usage
57+
if __name__ == "__main__":
58+
monkey = MonkeyHandler()
59+
squirrel = SquirrelHandler()
60+
dog = DogHandler()
61+
62+
monkey.set_next(squirrel).set_next(dog)
63+
64+
for food in ["Nut", "Banana", "Meat", "Apple"]:
65+
print(f"Client: Who wants a {food}?")
66+
result = monkey.handle(food)
67+
if result:
68+
print(result)
69+
else:
70+
print(f"No one wants the {food}.")
71+
```
72+
73+
## Summary
74+
Implementation of the Chain of Responsibility pattern in Python.
75+
76+
## Docstrings
77+
- Base Handler class with chaining support.
78+
- Sets the next handler in the chain and returns the next handler.
79+
- Abstract method to handle requests. Must be implemented by subclasses.
80+
- Handler for monkeys that can eat bananas.
81+
- Handler for squirrels that can eat nuts.
82+
- Handler for dogs that can eat meat.
83+

chunks/behavioral_command.md

Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
---
2+
file: behavioral/command.py
3+
chunk: behavioral_command.md
4+
---
5+
6+
```python
7+
"""
8+
Behavioral Pattern: Command
9+
10+
Encapsulates a request as an object, thereby allowing for parameterization of clients with queues,
11+
requests, and operations, and supports undoable actions.
12+
"""
13+
14+
from abc import ABC, abstractmethod
15+
16+
# Command interface
17+
class Command(ABC):
18+
@abstractmethod
19+
def execute(self) -> None:
20+
pass
21+
22+
# Receiver
23+
class Light:
24+
def turn_on(self) -> None:
25+
print("Light is ON")
26+
27+
def turn_off(self) -> None:
28+
print("Light is OFF")
29+
30+
# Concrete commands
31+
class TurnOnCommand(Command):
32+
def __init__(self, light: Light) -> None:
33+
self._light = light
34+
35+
def execute(self) -> None:
36+
self._light.turn_on()
37+
38+
class TurnOffCommand(Command):
39+
def __init__(self, light: Light) -> None:
40+
self._light = light
41+
42+
def execute(self) -> None:
43+
self._light.turn_off()
44+
45+
# Invoker
46+
class RemoteControl:
47+
def __init__(self) -> None:
48+
self._commands: list[Command] = []
49+
50+
def submit(self, command: Command) -> None:
51+
self._commands.append(command)
52+
command.execute()
53+
54+
# Example usage
55+
if __name__ == "__main__":
56+
light = Light()
57+
on_command = TurnOnCommand(light)
58+
off_command = TurnOffCommand(light)
59+
60+
remote = RemoteControl()
61+
remote.submit(on_command)
62+
remote.submit(off_command)
63+
64+
```
65+
66+
## Summary
67+
Implementation of the Command Design Pattern in Python
68+
69+
## Docstrings
70+
- Encapsulates a request as an object, allowing for parameterization of clients with queues, requests, and operations, and supports undoable actions.
71+
- Abstract base class representing a command. Must implement the execute method.
72+
- Concrete command that turns on a light.
73+
- Concrete command that turns off a light.
74+
- Abstract base class representing a receiver. Provides methods for turning on and off a light.
75+
- Class representing a remote control that can submit commands and execute them.
76+
- Example usage of the Command pattern to control a light.
77+

chunks/behavioral_interpreter.md

Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
---
2+
file: behavioral/interpreter.py
3+
chunk: behavioral_interpreter.md
4+
---
5+
6+
```python
7+
"""
8+
Behavioral Pattern: Interpreter
9+
10+
Defines a representation for a grammar and an interpreter that uses the representation
11+
to interpret sentences in the language. Useful for simple language parsing.
12+
"""
13+
14+
from __future__ import annotations
15+
from abc import ABC, abstractmethod
16+
from typing import Dict
17+
18+
# Context provides input for interpretation
19+
class Context:
20+
def __init__(self, variables: Dict[str, int]) -> None:
21+
self.variables = variables
22+
23+
# Abstract Expression
24+
class Expression(ABC):
25+
@abstractmethod
26+
def interpret(self, context: Context) -> int:
27+
pass
28+
29+
# Terminal Expression
30+
class Variable(Expression):
31+
def __init__(self, name: str) -> None:
32+
self.name = name
33+
34+
def interpret(self, context: Context) -> int:
35+
return context.variables.get(self.name, 0)
36+
37+
# Non-terminal Expressions
38+
class Add(Expression):
39+
def __init__(self, left: Expression, right: Expression) -> None:
40+
self.left = left
41+
self.right = right
42+
43+
def interpret(self, context: Context) -> int:
44+
return self.left.interpret(context) + self.right.interpret(context)
45+
46+
class Subtract(Expression):
47+
def __init__(self, left: Expression, right: Expression) -> None:
48+
self.left = left
49+
self.right = right
50+
51+
def interpret(self, context: Context) -> int:
52+
return self.left.interpret(context) - self.right.interpret(context)
53+
54+
# Example usage
55+
if __name__ == "__main__":
56+
context = Context({"x": 10, "y": 5})
57+
expr = Add(Variable("x"), Subtract(Variable("y"), Variable("z"))) # x + (y - z)
58+
print("Result:", expr.interpret(context))
59+
60+
```
61+
62+
## Summary
63+
This code defines a simple interpreter for a basic arithmetic language using the Interpreter pattern.
64+
65+
## Docstrings
66+
- Defines a representation for a grammar and an interpreter that uses the representation to interpret sentences in the language. Useful for simple language parsing.
67+
- Context provides input for interpretation
68+
- Abstract Expression
69+
- Terminal Expression
70+
- Non-terminal Expressions
71+
- Example usage
72+

chunks/behavioral_memento.md

Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
---
2+
file: behavioral/memento.py
3+
chunk: behavioral_memento.md
4+
---
5+
6+
```python
7+
"""
8+
Behavioral Pattern: Memento
9+
10+
Captures and externalizes an object's internal state so that it can be restored later,
11+
without violating encapsulation. Useful for undo mechanisms.
12+
"""
13+
14+
from __future__ import annotations
15+
from typing import List
16+
17+
# Memento
18+
class Memento:
19+
def __init__(self, state: str) -> None:
20+
self._state = state
21+
22+
def get_state(self) -> str:
23+
return self._state
24+
25+
# Originator
26+
class TextEditor:
27+
def __init__(self) -> None:
28+
self._state = ""
29+
30+
def write(self, text: str) -> None:
31+
self._state += text
32+
33+
def save(self) -> Memento:
34+
return Memento(self._state)
35+
36+
def restore(self, memento: Memento) -> None:
37+
self._state = memento.get_state()
38+
39+
def get_content(self) -> str:
40+
return self._state
41+
42+
# Caretaker
43+
class History:
44+
def __init__(self) -> None:
45+
self._history: List[Memento] = []
46+
47+
def backup(self, memento: Memento) -> None:
48+
self._history.append(memento)
49+
50+
def undo(self) -> Memento:
51+
return self._history.pop()
52+
53+
# Example usage
54+
if __name__ == "__main__":
55+
editor = TextEditor()
56+
history = History()
57+
58+
editor.write("Hello, ")
59+
history.backup(editor.save())
60+
61+
editor.write("world!")
62+
print("Current content:", editor.get_content())
63+
64+
editor.restore(history.undo())
65+
print("After undo:", editor.get_content())
66+
```
67+
68+
## Summary
69+
Implements the Memento design pattern for a text editor, allowing state restoration and undo functionality.
70+
71+
## Docstrings
72+
- Captures and externalizes an object's internal state so that it can be restored later, without violating encapsulation.
73+
- Initializes a Memento with a given state.
74+
- Returns the state stored in the Memento.
75+
- Initializes a TextEditor with an empty state.
76+
- Writes text to the editor, updating its internal state.
77+
- Saves the current state of the TextEditor as a Memento.
78+
- Restores the TextEditor's state from a given Memento.
79+
- Returns the current content of the TextEditor.
80+
- Initializes a History to keep track of Mementos.
81+
- Adds a Memento to the history list.
82+
- Removes and returns the last Memento from the history list.
83+

0 commit comments

Comments
 (0)