Skip to content

Instantly share code, notes, and snippets.

@mjamroz
Created February 10, 2023 10:54
Show Gist options
  • Save mjamroz/0ea5eb90a3cbca58490af3280c9645c0 to your computer and use it in GitHub Desktop.
Save mjamroz/0ea5eb90a3cbca58490af3280c9645c0 to your computer and use it in GitHub Desktop.
check parent function
import functools
import inspect
def run_job_in_background(func, args, kwargs):
print(f"RUN {func} background")
func()
def background(func=None, *, commit=False):
"""Run function in background"""
if func is None:
return functools.partial(background, commit=commit)
def commit_after(func):
"""Exec commit after"""
def wrapper(*args, **kwargs):
"""Wrapper"""
result = func(*args, **kwargs)
print("would commit ")
return result
return wrapper
def _safe_cast(arg):
return arg
@functools.wraps(func)
def wrapper(*args, **kwargs):
for frame in inspect.getouterframes(inspect.currentframe()):
if frame.function == "run_job_in_background":
print(f"RUN {func} SERIAL")
func(*args, **kwargs)
break
else:
run_job_in_background(
func if not commit else commit_after(func),
[_safe_cast(arg) for arg in args],
{key: _safe_cast(arg) for key, arg in kwargs.items()},
)
return wrapper
@background
def a():
print("jestem a")
@background
def b():
print("jestem b")
a()
@background
def c():
print("jestem c")
b()
print(50 * "@", "run a in the background ")
a()
print(50 * "@", "run b in the background")
b()
print(50 * "@", "run c in the background")
c()
"""
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ run a in the background
RUN <function a at 0x7f26de09ad40> background
jestem a
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ run b in the background
RUN <function b at 0x7f26de09af80> background
jestem b
RUN <function a at 0x7f26de09ad40> SERIAL
jestem a
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ run c in the background
RUN <function c at 0x7f26de09b1c0> background
jestem c
RUN <function b at 0x7f26de09af80> SERIAL
jestem b
RUN <function a at 0x7f26de09ad40> SERIAL
jestem a
"""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment