Last active
June 4, 2022 13:13
-
-
Save xflr6/32ba3f01f56182525193791206c49565 to your computer and use it in GitHub Desktop.
Decorator with an optional parameter
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
"""Decorator with an optional parameter.""" | |
from collections.abc import Callable | |
import functools | |
from typing import Optional | |
FUNCS = {} | |
def register(func: Optional[Callable] = None, | |
name: Optional[str] = None) -> Callable: | |
if func is None: | |
return functools.partial(register, name=name) | |
if name is None: | |
name = func.__name__ | |
FUNCS[name] = func | |
return func | |
@register | |
def spam(): | |
pass | |
@register(name='eggs') | |
def _eggs(): | |
pass | |
assert FUNCS == {'spam': spam, 'eggs': _eggs} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment