0

I want do define a Python function with exec like this:

exec """def my_func(alpha = 'a'):
  return alpha"""

It works. However, for a specific reason I want to to define the alpha = 'a' in a separate string:

s = "alpha = 'a'"
exec """def my_func(s):
  return alpha"""

but this one doesn't work. Is there a way to insert a string variable content into multiline comment string this way?

3
  • 1
    Why are you doing this with exec? What is your actual use case? Commented Nov 13, 2017 at 8:56
  • Possible duplicate of How do I put a variable inside a String in Python? Commented Nov 13, 2017 at 8:57
  • 2
    This is not a "multiline comment", it's a triple quoted (multiline) string literal. The fact that triple quoted strings are often used as docstrings does not make them comments. And since it's a string literal, all the usual string formatting operations (which are extensively documented) are available. Commented Nov 13, 2017 at 9:01

1 Answer 1

5

Use the format function:

s = "alpha = 'a'"
exec """def my_func({}):
  return alpha""".format(s)
Sign up to request clarification or add additional context in comments.

Comments

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.