|
1517 | 1517 | "#export\n", |
1518 | 1518 | "def with_cast(f):\n", |
1519 | 1519 | " \"Decorator which uses any parameter annotations as preprocessing functions\"\n", |
1520 | | - " anno,params = annotations(f),argnames(f)\n", |
| 1520 | + " anno, out_anno, params = annotations(f), anno_ret(f), argnames(f)\n", |
| 1521 | + " c_out = ifnone(out_anno, noop)\n", |
1521 | 1522 | " defaults = dict(zip(reversed(params), reversed(f.__defaults__ or {})))\n", |
1522 | 1523 | " @functools.wraps(f)\n", |
1523 | 1524 | " def _inner(*args, **kwargs):\n", |
|
1528 | 1529 | " if v in kwargs: kwargs[v] = c(kwargs[v])\n", |
1529 | 1530 | " elif i<len(args): args[i] = c(args[i])\n", |
1530 | 1531 | " elif v in defaults: kwargs[v] = c(defaults[v])\n", |
1531 | | - " return f(*args, **kwargs)\n", |
| 1532 | + " return c_out(f(*args, **kwargs))\n", |
1532 | 1533 | " return _inner" |
1533 | 1534 | ] |
1534 | 1535 | }, |
|
1539 | 1540 | "outputs": [], |
1540 | 1541 | "source": [ |
1541 | 1542 | "@with_cast\n", |
1542 | | - "def _f(a, b:Path, c:str='', d=0)->bool: return (a,b,c,d)\n", |
| 1543 | + "def _f(a, b:Path, c:str='', d=0): return (a,b,c,d)\n", |
1543 | 1544 | "\n", |
1544 | 1545 | "test_eq(_f(1, '.', 3), (1,Path('.'),'3',0))\n", |
1545 | | - "test_eq(_f(1, '.'), (1,Path('.'),'',0))" |
| 1546 | + "test_eq(_f(1, '.'), (1,Path('.'),'',0))\n", |
| 1547 | + "\n", |
| 1548 | + "@with_cast\n", |
| 1549 | + "def _g(a:int=0)->str: return a\n", |
| 1550 | + "\n", |
| 1551 | + "test_eq(_g(4.0), '4')\n", |
| 1552 | + "test_eq(_g(4.4), '4')\n", |
| 1553 | + "test_eq(_g(2), '2')" |
1546 | 1554 | ] |
1547 | 1555 | }, |
1548 | 1556 | { |
|
4851 | 4859 | { |
4852 | 4860 | "data": { |
4853 | 4861 | "text/plain": [ |
4854 | | - "64" |
| 4862 | + "12" |
4855 | 4863 | ] |
4856 | 4864 | }, |
4857 | 4865 | "execution_count": null, |
|
0 commit comments