0

Example function:

def my_function():if 9>8 print("Hello from a function") else print("Goodbye")

Expected Output:

String : """def my_function(): if 9>8 print("Hello from a function") else print("Goodbye")"""

Includes the reserved words (def,if,else) as well.

martineau
124k29 gold badges181 silver badges319 bronze badges
asked Oct 21, 2021 at 7:24
1
  • 1
    The definition of your example function is syntactically invalid. Commented Oct 21, 2021 at 8:41

1 Answer 1

3

Use inspect.getsource()

As pointed out by @martineau (thx), your function had a SyntaxError. I reformatted your function and used a ternary to keep it single-line.

 import inspect 
 def my_function(): print("Hello from a function") if 9>8 else print("Goodbye")
 print(inspect.getsource(my_function))

Output:

def my_function(): if 9>8 print("Hello from a function") else print("Goodbye")

answered Oct 21, 2021 at 7:33
Sign up to request clarification or add additional context in comments.

3 Comments

This does not work because the function definition is a SyntaxError.
@martineau ah yes you're right about the function syntax - corrected it
...and I think it is something you should mention in your answer.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.