Last active
October 26, 2022 13:35
-
-
Save frenata/8858885bd9eebe0995a8911ac317c5ee to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
__foo = None | |
class Foo: | |
def __init__(self, x): | |
self.x = x | |
def init_global_foo(x): | |
global __foo | |
__foo = Foo(x) | |
def with_foo(foo=None): | |
def decorator(func): | |
def inject(foo): | |
def wrapper(*args, **kwargs): | |
# this wrapper could do anything at this point | |
# but here's a simple arg injection example | |
return func(*args, **kwargs, x=foo.x) | |
return wrapper | |
global __foo | |
if foo is not None: | |
return inject(foo) | |
elif __foo is not None: | |
return inject(__foo) | |
else: | |
raise ValueError("foo is undefined") | |
return decorator | |
if __name__ == "__main__": | |
# decorate with a init once style | |
init_global_foo(99) | |
@with_foo() | |
def f(x): | |
print(x) | |
# decorate with a init on decorate style | |
@with_foo(Foo(42)) | |
def g(x): | |
print(x) | |
@with_foo(Foo(43)) | |
def h(x): | |
print(x) | |
f() | |
g() | |
h() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment