简体   繁体   中英

How to set the signature of a function?

I tried changing the signature of a function using the inspect module:

import inspect

def some_func(a, b):
    return

sig = inspect.signature(some_func)
new_params = list(sig.parameters.values()) + [inspect.Parameter('c', inspect._ParameterKind.POSITIONAL_OR_KEYWORD)]
new_sig = sig.replace(parameters=new_params)
some_func.__signature__ = new_sig

When I inspect the function's signature, it shows the new signature:

>>> inspect.signature(some_func)
>>> <Signature (a, b, c)>

But when I try to call the function according to the new signature, I get a TypeError:

>>> some_func(1, 2, 3)
>>> TypeError: some_func() takes 2 positional arguments but 3 were given

How can I set the signature so that the interpreter checks the arguments against the new signature instead of the original one?

Reassigning function signatures is not something Python supports.

Most functions do something with their arguments. If you somehow managed to change a function's signature, the function body wouldn't have the right arguments to work with. It's not a thing that makes sense to do.

If you're absolutely adamant about doing this anyway, you'd have to do something like mess with the function's __code__ . This is a low-level implementation detail, and messing with it this way is likely to crash Python or worse.

I think this is a category error. You can create a Signature object by inspecting an existing function, but you can't assign an existing function a new signature the way you're trying to do.

That is, hasattr(some_func, '__signature__') returns False . You assigned it in your script, but you can assign arbitrary attributes to functions.

To actually create a function that modifies an existing function you'll have to wrap it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM