Skip to content

Commit

Permalink
Add observer pattern and two decorator pattern examples
Browse files Browse the repository at this point in the history
  • Loading branch information
piotrgredowski authored and pgred-orsted committed Sep 9, 2024
1 parent 4a339e4 commit a2fa2ec
Show file tree
Hide file tree
Showing 7 changed files with 937 additions and 231 deletions.
6 changes: 5 additions & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,11 @@
name = "python-samples"
version = "0.1.0"
description = "Monorepo for my Python code samples for talks, presentations, workshops, demos."
dependencies = ["fastapi[uvicorn]>=0.100.0", "uvicorn[standard]>=0.23.1"]
dependencies = [
"fastapi[uvicorn]>=0.100.0",
"uvicorn[standard]>=0.23.1",
"numpy",
]
readme = "README.md"
requires-python = ">= 3.8"

Expand Down
181 changes: 0 additions & 181 deletions requirements-dev.lock

This file was deleted.

49 changes: 0 additions & 49 deletions requirements.lock

This file was deleted.

43 changes: 43 additions & 0 deletions src/essentials/05_patterns/decorator_pattern.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import functools
import typing


def make_bold(func: typing.Callable[..., str]) -> typing.Callable[..., str]:
def wrapper(*args, **kwargs):
return f"\033[1m{func(*args, **kwargs)}\033[0m"
return wrapper


def make_cyan(func: typing.Callable[..., str]) -> typing.Callable[..., str]:
# https://docs.python.org/3/library/functools.html#functools.wraps
@functools.wraps(func)
def wrapper(*args, **kwargs):
return f"\033[96m{func(*args, **kwargs)}\033[0m"
return wrapper

if __name__ == "__main__":

def greet_raw(name):
return f"Hello, {name}!"

@make_bold
def greet_with_decorator(name):
return f"Hello, {name}!"


greet_bold = make_bold(greet_raw)
greet_cyan = make_cyan(greet_raw)

text = "Hello, World!"

print(text)
print(greet_raw(text))
print(greet_bold(text))
print(greet_with_decorator(text))
print(greet_cyan(text))


print(greet_bold.__name__)
print(greet_cyan.__name__)

pass
79 changes: 79 additions & 0 deletions src/essentials/05_patterns/decorator_pattern_2.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
import functools
import inspect
import pathlib
import time
import typing
from math import log


def measure_time(func: typing.Callable[..., typing.Any]) -> typing.Callable[..., typing.Any]:
@functools.wraps(func)
def wrapper(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
end = time.time()
print(f"Execution time: {end - start} s")
return result
return wrapper






def measure_time_2(log_to_file: bool = False, log_file: str = "_execution_times.log"):
def decorator(func: typing.Callable) -> typing.Callable:
@functools.wraps(func)
def wrapper(*args: typing.Any, **kwargs: typing.Any) -> typing.Any:
start_time = time.time()
result = func(*args, **kwargs)
end_time = time.time()
execution_time = end_time - start_time

file_path = pathlib.Path(inspect.getfile(func)).resolve()
line_number = inspect.getsourcelines(func)[1]

message = f"Function '{func.__name__}' from file '{file_path}:{line_number}' took {execution_time:.4f} seconds to execute."

if log_to_file:
with open(log_file, 'a') as f:
f.write(message + '\n')
else:
print(message)

return result
return wrapper
return decorator


if __name__ == "__main__":

@measure_time
def slow_function():
import time
time.sleep(1)
return "Done!"

@measure_time_2(log_to_file=True, log_file="_slow_functions.txt")
def another_slow_function(x: int, y: int) -> int:
time.sleep(1.1)
return x + y

@measure_time_2()
def my_function():
time.sleep(1.2)
return "My function"

@measure_time_2(log_to_file=True)
def my_function_2():
time.sleep(0.6)
return "My function 2"

print(slow_function())
print()
print(another_slow_function(1, 2))
print()
print(my_function())
print()
print(my_function_2())
pass
Loading

0 comments on commit a2fa2ec

Please sign in to comment.