Skip to content

Commit 362eb4f

Browse files
author
Sylvain MARIE
committed
Moved auto signature string to Signature object conversion to wraps. Added a test.
1 parent 91a9a2c commit 362eb4f

File tree

2 files changed

+26
-6
lines changed

2 files changed

+26
-6
lines changed

src/makefun/main.py

Lines changed: 11 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -278,11 +278,6 @@ def create_function(func_signature, # type: Union[str, Signature]
278278
else:
279279
raise TypeError("Invalid type for `func_signature`: %s" % type(func_signature))
280280

281-
if isinstance(attrs.get('__signature__'), str):
282-
# __signature__ must be a Signature object, so if it is a string,
283-
# we need to evaluate it.
284-
attrs['__signature__'] = get_signature_from_string(attrs['__signature__'], evaldict)[1]
285-
286281
# extract all information needed from the `Signature`
287282
params_to_kw_assignment_mode = get_signature_params(func_signature)
288283
params_names = list(params_to_kw_assignment_mode.keys())
@@ -970,7 +965,17 @@ def _get_args_for_wrapping(wrapped, new_sig, remove_args, prepend_args, append_a
970965
# PEP362: always set `__wrapped__`, and if signature was changed, set `__signature__` too
971966
all_attrs["__wrapped__"] = wrapped
972967
if has_new_sig:
973-
all_attrs["__signature__"] = func_sig
968+
if isinstance(func_sig, Signature):
969+
all_attrs["__signature__"] = func_sig
970+
else:
971+
# __signature__ must be a Signature object, so if it is a string we need to evaluate it.
972+
frame = _get_callerframe(offset=1)
973+
evaldict, _ = extract_module_and_evaldict(frame)
974+
# Here we could wish to directly override `func_name` and `func_sig` so that this does not have to be done
975+
# again by `create_function` later... Would this be risky ?
976+
_func_name, func_sig_as_sig, _ = get_signature_from_string(func_sig, evaldict)
977+
all_attrs["__signature__"] = func_sig_as_sig
978+
974979
all_attrs.update(attrs)
975980

976981
return func_name, func_sig, doc, qualname, co_name, module_name, all_attrs

tests/test_advanced.py

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -245,3 +245,18 @@ def foo(a):
245245
return a
246246

247247
assert foo(10) == 10
248+
249+
250+
@pytest.mark.skipif(sys.version_info < (3, 5), reason="requires python 3.5 or higher (non-comment type hints)")
251+
def test_type_hint_error_sigchange():
252+
""" Test for https://github.com/smarie/python-makefun/issues/32 """
253+
254+
from tests._test_py35 import make_ref_function
255+
from typing import Any
256+
ref_f = make_ref_function()
257+
258+
@wraps(ref_f, new_sig="(a: Any)")
259+
def foo(a):
260+
return a
261+
262+
assert foo(10) == 10

0 commit comments

Comments
 (0)