0

So I have a piece of code such as

def math():
    x = 2
    y = 4
    z = x + y

What I'd like to be able to do is print out the contents of this function somehow, so that what appears in the output window is:

 x = 2
 y = 4
 z = x + y

How could I print this out as a string from the function?

I tried things such as:

print(math())

but that just calls the function or

print(math)

which doesn't give my anything. And

print("math()")

just prints out the name.

Barmar
  • 741,623
  • 53
  • 500
  • 612
  • To clarify, you want to print out the actual lines of code in your function as raw text? – UnsanitizedInput May 05 '23 at 16:11
  • @UnsanitizedInput yes exactly, as if I'm printing the contents as a string. – Petar Pehchevski May 05 '23 at 16:13
  • 1
    May I ask what the reason for wanting to do this is? – UnsanitizedInput May 05 '23 at 16:15
  • @UnsanitizedInput So basically this functions will be executed by a pressing a button on a UI, but I'll have a section in my UI where a person can click a button and generate the code from the function, essentially isolating the code from the overall UI, but for them to copy the code it'll need to be printed out on the output. Because some people using the script may want to bind the code to a hotkey and use it that way, instead of having to go to the UI every time and clicking the button. Hope that makes sense. – Petar Pehchevski May 05 '23 at 16:21
  • @Cireo from what I've seen, that solutions works on imported functions only, not ones that are defined within the interactive prompt – Petar Pehchevski May 05 '23 at 16:25
  • [this answer](https://stackoverflow.com/a/27458391/1491895) shows how to do it for functions defined interactively. – Barmar May 05 '23 at 16:30
  • The solutions don't work more generally because Python simply doesn't always save the source code anywhere. – Barmar May 05 '23 at 16:31

0 Answers0