0

I have a Python class with several different methods doing different things, but I'd like each of them, when it runs, to save its name and argument values, so that I can use them later. One way I found is to add something like this to each of them:

frame = inspect.currentframe()
args, _, _, values = inspect.getargvalues(frame)
function_name = inspect.getframeinfo(frame)[2]
function_meta = {arg: values[arg] for arg in args}
self.meta[function_name] = function_meta

This is fine, however, I'd prefer to keep it DRY and don't have to copy/paste this identical snippet to every method I add.

Alternatively, I could turn it into a separate function save_meta(), but then inspect will return the data of save_meta(), instead of the function that called it, right? Is there any elegant and reusable way of solving this?

1 Answer 1

1

You only seem to be dependent on the current frame for the inspect. I would suggest

def save_meta(frame):
    args, _, _, values = inspect.getargvalues(frame)
    function_name = inspect.getframeinfo(frame)[2]
    function_meta = {arg: values[arg] for arg in args}
    self.meta[function_name] = function_meta

And call it with

save_meta(inspect.currentframe())
Sign up to request clarification or add additional context in comments.

5 Comments

Ah damn, you're right, that was pretty basic. :) Thanks! Bonus question: is there any easier way to do this?
@machaerus Sorry, I saw your question just now. What do you mean with easier?
I thought that maybe there's a way to do this without writing a custom function. It seems like a pretty basic functionality, I'm kinda surprised there's no built-in method for this.
@machaerus Nothing that I've heard of I'm afraid. If you use it often I guess you could make a super class to subclass from? Otherwise, at least it is quite short :)
Ok, this method does the trick here, I was just curious. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.