Skip to content

Instantly share code, notes, and snippets.

@dutc
Created June 14, 2018 21:36
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save dutc/113f3c1c55d62fc4e7422cc49c9ebaaa to your computer and use it in GitHub Desktop.
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/)
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