Invited Keynote Talk from PyCon Israel, June 12, 2017. I cause trouble and build a framework using all sorts of new Python 3.6+ features.
이 글의 핵심은 ‘Python 3.6 을 최대한 활용’ 이다! 저자는 type checking, validation 등을 간편하게 할 수 있는 방법을 소개한다.
>>> born = 1991>>> died = 2016>>> print(f'RIP: {born} - {died}')RIP: 1991 - 2016>>> f'{born}''1991'>>> f"{f'Age {died - born}':*^25}"'*********Age 25**********'
중간 과정은 생략하고, 최종 코드.
# contract.pyclass Contract:@classmethoddef check(cls, value):passclass Typed(Contract):@classmethoddef check(cls, value):assert isinstance(value, cls.type), f'Expected {cls.type}'super().check(value)class Integer(Typed):type = intclass Float(Typed):type = floatclass String(Typed):type = strclass Positive(Contract):@classmethoddef check(cls, value):assert value > 0, 'Must be > 0'super().check(value)class PositiveInteger(Integer, Positive):pass
from functools import wrapsfrom inspect import signaturedef checked(func):sig = signature(func)ann = func.__annotations__@wraps(func)def wrapper(*args, **kwargs):bound = sig.bind(*args, **kwargs)for name, val in bound.arguments.items():if name in ann:ann[name].check(val)return func(*args, **kwargs)return wrapper
>>> from inspect import signature>>> signature(gcd)<Signature (a:__main__.PositiveInteger, b:__main__.PositiveInteger)>>>> signature(gcd).bind(1, 4)<BoundArguments (a=1, b=4)>>>> signature(gcd).bind(1, 4).argumentsOrderedDict([('a', 1), ('b', 4)])
@checkeddef gcd(a: PositiveInteger, b: PositiveInteger):while b:a, b = b, a % breturn a