I would like to store the exact string that was typed for a function call, from the function itself using introspection (I cannot/don't want to hack the command line interpreter -- so, for example getting history from readline or whatever is not what I am looking for).
Let's say, if user typed:
>>> myfunc('a', 'b', 1, mykwarg='hello')
I would like to get the call string (i.e. myfunc('a', 'b', 1, mykwarg='hello'))
from the code inside myfunc.
I can craft something like this:
def myfunc(a,b,c,mykwarg=None):
frame = inspect.currentframe()
sig = inspect.signature(myfunc)
args = []
for param in sig.parameters.values():
if param.name in frame.f_locals:
args.append(f"{param.name}={str(frame.f_locals[param.name])}")
cmd = f"{frame.f_code.co_name}({','.join(args)})"
print(cmd)
I get:
>>> myfunc('a', 'b', 1, mykwarg='hello')
myfunc(a=a,b=b,c=1,mykwarg=hello)
Which is not exactly what user typed. Also, I hope there is something more robust and less 'hackish' to try...
Use case: I want to be able to associate a command call from my library with its result. I do not want to hard-code the command call storage for each function, I would prefer to use a decorator or something like that. This is probably much easier to do from the REPL, but I would like to not depend on it (like, if user calls the function from its own program, it should still be able to associate the command call with the result).
myfunc('a', 'b', 1, mykwarg='hello'), or the equivalentmyfunc(a=a,b=b,c=1,mykwarg=hello), you can always retrofit the quotes, and strip the named argument association? What's your use-case? Are you simply playing around with the REPL, or does it actually break anything? (if so, provide an example and explain what it breaks and why) And can you give any compelling reason why not use the REPL? If not, this isn't really a real question, IMO.