Commit MetaInfo

Revisiondfd25e05df712bb78d15ad6169a3fad6f5a39632 (tree)
Time2022-07-11 22:41:48
AuthorAntoon Pardon <aej@pard...>
CommiterAntoon Pardon

Log Message

Added the forgotten decorator file

Change Summary

Incremental Difference

diff -r ffef4e4eff62 -r dfd25e05df71 source/decorators.py
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/source/decorators.py Mon Jul 11 15:41:48 2022 +0200
@@ -0,0 +1,31 @@
1+# pylint: disable=missing-module-docstring,unused-argument,unused-variable
2+
3+from inspect import signature as signature_of, Parameter
4+from functools import wraps
5+from copy import copy
6+
7+def copy_defaults(func):
8+ """
9+ first approximation for copying default argument values.
10+ """
11+
12+ signature = signature_of(func)
13+ parameter_items = list(signature.parameters.items())
14+
15+ @wraps(func)
16+ def wrapper(*args, **kwds):
17+ newargs = list(args)
18+ tail_parameters = parameter_items[len(args):]
19+ for name, parameter in tail_parameters:
20+ try:
21+ newargs.append(kwds[name])
22+ del kwds[name]
23+ except KeyError:
24+ if parameter.default is not Parameter.empty:
25+ newargs.append(copy(parameter.default))
26+ else:
27+ #return func(*newargs, **kwds)
28+ break
29+ return func(*newargs, **kwds)
30+
31+ return wrapper
diff -r ffef4e4eff62 -r dfd25e05df71 source/release.cfg
--- a/source/release.cfg Mon Jul 11 14:59:27 2022 +0200
+++ b/source/release.cfg Mon Jul 11 15:41:48 2022 +0200
@@ -1,3 +1,3 @@
1-version = '0.01.08f'
2-modified = '2022-07-11 @ 14:58:24'
1+version = '0.01.09d'
2+modified = '2022-07-11 @ 15:38:48'
33 installed = '*********************'
diff -r ffef4e4eff62 -r dfd25e05df71 tests/decorators.py
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/tests/decorators.py Mon Jul 11 15:41:48 2022 +0200
@@ -0,0 +1,40 @@
1+#pylint: disable=invalid-name,no-self-argument,missing-function-docstring,(missing-module-docstring,dangerous-default-value)
2+
3+from unittest import TestCase, main as unitmain
4+
5+from AGPlib.decorators import copy_defaults
6+
7+@copy_defaults
8+def append_range(nr, lst = []):
9+ lst.extend(range(nr))
10+ return lst
11+
12+@copy_defaults
13+def ident(a = 1):
14+ return a
15+
16+class InspectCase(TestCase):
17+ """
18+ class for inspecting decorators
19+ """
20+
21+ def test_copy_defaults(s):
22+ s.assertEqual(1, ident())
23+ s.assertEqual([0, 1, 2], append_range(3))
24+ s.assertEqual([0, 1, 2, 3, 4], append_range(5))
25+ s.assertEqual(['a', 0], append_range(1, ['a']))
26+
27+ def test_copy_defaults_with_keyword(s):
28+ s.assertEqual(['a', 0], append_range(1, lst = ['a']))
29+
30+ def test_too_many_arguments(s):
31+ # pylint: disable=too-many-function-args
32+ with s.assertRaises(TypeError):
33+ append_range(1, [], 4)
34+
35+ def test_too_few_arguments(s):
36+ # pylint: disable=no-value-for-parameter
37+ with s.assertRaises(TypeError):
38+ append_range()
39+
40+unitmain()
Show on old repository browser