Last active
December 30, 2020 09:22
-
-
Save horvatha/5400bc2739d793e03a95616a23c84cc1 to your computer and use it in GitHub Desktop.
Decorator for registering a function with key. It was wrong (until version 3), but now it works, thanks Real Python and Kryssz90
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
import functools | |
import unittest | |
from typing import Callable | |
class LoaderFactory: | |
def __init__(self) -> None: | |
self.registered_functions = dict( | |
) | |
def get_loader_function(self, registeredName: str) -> Callable: | |
return self.registered_functions.get(registeredName, default_function) | |
def register_loader_function(self, registeredName: str, function: Callable) -> None: | |
self.registered_functions[registeredName] = function | |
private_property_factory = LoaderFactory() | |
def default_function(x): | |
return 3*x | |
def register(registeredName): | |
"""Registers the loader function""" | |
def decorator_register(func): | |
private_property_factory.register_loader_function(registeredName, func) | |
@functools.wraps(func) | |
def wrapper(*args, **kwargs): | |
print(3, private_property_factory.registered_functions) | |
value = func(*args, **kwargs) | |
return value | |
return wrapper | |
print(2, private_property_factory.registered_functions) | |
return decorator_register | |
@register('StartProcess') | |
def function1(x): | |
return 2*x | |
print(1, private_property_factory.registered_functions) | |
print(4, private_property_factory.get_loader_function("StartProcess")(15)) # Doesn't print the registered functions, function1 was registered without the wrapper. | |
print(5, function1(15)) # It prints the registered functions, as we call the wrapped function. | |
class MyTestCase(unittest.TestCase): | |
def test_something(self): | |
self.assertIn('StartProcess', private_property_factory.registered_functions) | |
if __name__ == '__main__': | |
unittest.main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
It's worth to try what will be the output of this script.
There is five print statements starting with print(1,..., print(2,... ... print(5, ...). What will be the order of this prints.