Is there a reverse operation in Python's inspect.getcallargs in the standard library?

Is there any way to return from the return value from inspect.getcallargs(func) to the *args, **kw pair, which can really be used to call func ?

Use case: let's say I'm writing a decorator, and I want to change a specific function argument by name. Here is the beginning of some code for this:

 @fix_x def a(x): print x @fix_x def b(**q): print q['x'] def fix_x(func): def wrapper(*args, **kw): argspec = inspect.getargspec(func) callargs = inspect.getcallargs(func, *args, **kw) if 'x' in callargs: callargs['x'] += 5 elif 'x' in callargs[argspec.keywords]: callargs[argspec.keywords]['x'] += 5 # ...and now I'd like a simple way to call func with callargs...? 

(I'm actually doing something more complex with the challenges between making them and wanting to call them, but this should give an idea of ​​what I'm looking for.)

+4
source share
2 answers

No, there is currently no good way to do this, however it works in Python 3.3!

See PEP 362 - Function Signature Object for how this new function will work.

+3
source

I wrote my own code (more or less) for this. It is located in ArgSpec.make_call_args at https://github.com/codemage/wmpy

The semantics are slightly different; namely, it will still bypass any unknown arguments in ** kw instead of accepting a separate record identifier named after the ** kw parameter, but this is easy enough to change if I ever need to.

With a little effort, this could probably be turned into a pretty complete "backport" (in quotation marks, since it clearly did not separate the code) PEP 362 in Python 2.7. It does not execute parameters only for the keyword, but they do not exist at all in 2.x, so this will not affect the completeness of the API, and the verification module provides all other non-trivial mechanisms.

0
source

Source: https://habr.com/ru/post/1416694/


All Articles