Created
June 14, 2018 21:36
-
-
Save dutc/113f3c1c55d62fc4e7422cc49c9ebaaa to your computer and use it in GitHub Desktop.
PEP 563 -- Postponed Evaluation of Annotations (https://www.python.org/dev/peps/pep-0563/)
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
from __future__ import annotations | |
from inspect import signature | |
from functools import wraps | |
from collections import namedtuple | |
opt = namedtuple('Optional', '')() | |
def better_defaults(f): | |
sig = signature(f) | |
@wraps(f) | |
def func(*args, **kwargs): | |
ba = sig.bind(*args, **kwargs) | |
ba.apply_defaults() | |
kwargs.update({name: eval(f.__annotations__[name], ba.arguments.copy()) | |
for name, val in ba.arguments.items() if val is opt}) | |
return f(*args, **kwargs) | |
return func | |
@better_defaults | |
def f(x: y * 10 = opt, | |
y: x * 100 = opt, | |
z = 10): | |
return x + y + z | |
print(f'f(x=1) {f(1)}') | |
print(f'f(x=1) {f(x=1)}') | |
print(f'f(y=2) {f(y=2)}') | |
print(f'f(x=1) {f(1, z=3)}') | |
print(f'f(x=1) {f(1, y=2, z=3)}') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment