On 2019-10-19 00:31, Sümer Cip wrote:
I have been working on some feature of a deterministic profiler(github.com/sumerc/yappi http://github.com/sumerc/yappi). The feature is about getting arguments for a given set of function names. For example: you can define something like foo 1,3,arg_name and when foo function is called, profiler will simply collect the first, third from *args and a named argument arg_name from *kwargs.
For Python functions I am using following approach: Please note that the code below is executing in the PyTrace_CALL event of the profiler in C side: Look co_argcount and co_varnames to determine the names of arguments and then use these names to retrieve values from f_locals. It seems to be working fine for now. My first question is: Is there a better way to do this?
And for C functions, I am totally in dark. I have played with f_valuestack and retrieve some values from there but the indexes seem to change from Python version to version and also I think there is no way of getting named arguments...
I have been dealing with this for a while, so there might be unclear points in my explanation. I would really appreciate if anyone can help me on a correct direction on this.
Hi, The best way we know of getting a callable's arguments is inspect.signature: https://docs.python.org/3.5/library/inspect.html#inspect.signature
Of course, some callables can lie about their arguments, some might have information missing, and sometimes there even are good reasons to do such things. If you can't use inspect.signature directly, your best bet is probably to study its implementation. It's complex but hopefully well-enough commented. Just be aware it can change in the future, as we find better ways of documenting and finding signatures. And if you find a possible improvement, send it here!