-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdecorators.py
More file actions
36 lines (25 loc) · 807 Bytes
/
decorators.py
File metadata and controls
36 lines (25 loc) · 807 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import functools
import sys
import typing as t
Function = t.Callable[..., t.Any]
def redirect_to_file(filename: str) -> t.Callable[[Function], Function]:
def redirect_wrapper(func: Function) -> Function:
@functools.wraps(func)
def wrapper(*args: t.Any, **kwargs: t.Any) -> t.Any:
orig_stdout = sys.stdout
with open(filename, "a") as file:
sys.stdout = file
result = func(*args, **kwargs)
sys.stdout = orig_stdout
return result
return wrapper
return redirect_wrapper
@redirect_to_file("test.log")
def thingy() -> None:
print("hello!")
@redirect_to_file("test.log")
def thingy_with_args(name: str) -> None:
print(f"hello {name}!")
print(thingy)
thingy()
thingy_with_args("bob")