Message382120
Let's wait for Nick.
I have found great examples to show how decorator_factory can simplify things.
dataclasses.dataclass
```
def dataclass(cls=None, /, *, init=True, repr=True, eq=True, order=False,
unsafe_hash=False, frozen=False):
def wrap(cls):
return _process_class(cls, init, repr, eq, order, unsafe_hash, frozen)
# See if we're being called as @dataclass or @dataclass().
if cls is None:
# We're called with parens.
return wrap
# We're called as @dataclass without parens.
return wrap(cls)
```
```
@functools.decorator_factory
def dataclass(cls, /, *, init=True, repr=True, eq=True, order=False,
unsafe_hash=False, frozen=False):
return _process_class(cls, init, repr, eq, order, unsafe_hash, frozen)
```
functools.lru_cache
```
def lru_cache(maxsize=128, typed=False):
if isinstance(maxsize, int):
# Negative maxsize is treated as 0
if maxsize < 0:
maxsize = 0
elif callable(maxsize) and isinstance(typed, bool):
# The user_function was passed in directly via the maxsize argument
user_function, maxsize = maxsize, 128
wrapper = _lru_cache_wrapper(user_function, maxsize, typed, _CacheInfo)
wrapper.cache_parameters = lambda : {'maxsize': maxsize, 'typed': typed}
return update_wrapper(wrapper, user_function)
elif maxsize is not None:
raise TypeError(
'Expected first argument to be an integer, a callable, or None')
def decorating_function(user_function):
wrapper = _lru_cache_wrapper(user_function, maxsize, typed, _CacheInfo)
wrapper.cache_parameters = lambda : {'maxsize': maxsize, 'typed': typed}
return update_wrapper(wrapper, user_function)
return decorating_function
```
```
@decorator_factory
def lru_cache(user_function, /, maxsize=128, typed=False):
if isinstance(maxsize, int):
# Negative maxsize is treated as 0
if maxsize < 0:
maxsize = 0
elif maxsize is not None:
raise TypeError(
'Expected first argument to be an integer, a callable, or None')
wrapper = _lru_cache_wrapper(user_function, maxsize, typed, _CacheInfo)
wrapper.cache_parameters = lambda : {'maxsize': maxsize, 'typed': typed}
return update_wrapper(wrapper, user_function)
``` |
|
Date |
User |
Action |
Args |
2020-11-30 08:31:05 | uriyyo | set | recipients:
+ uriyyo, rhettinger, ncoghlan, serhiy.storchaka |
2020-11-30 08:31:05 | uriyyo | set | messageid: <1606725065.68.0.497251775054.issue42455@roundup.psfhosted.org> |
2020-11-30 08:31:05 | uriyyo | link | issue42455 messages |
2020-11-30 08:31:05 | uriyyo | create | |
|