Created
March 5, 2020 12:17
-
-
Save Kaundur/c449dc6356226381d034ba32d46ac3ef to your computer and use it in GitHub Desktop.
Python decorator with function registration
This file contains 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
def make_registrar(): | |
registry = {} | |
def registrar(func): | |
registry[func.__name__] = func | |
def wrapper(*args, **kwargs): | |
# Note - Modify function here | |
return func(*args, **kwargs) | |
return wrapper | |
registrar.all = registry | |
return registrar | |
reg = make_registrar() | |
@reg | |
def f1(a): | |
return a | |
@reg | |
def f2(a, b): | |
return a+b | |
print(reg.all) | |
# >>> {'f2': <function f2 at ...>, 'f1': <function f1 at ...>} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment