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?

Hendrik
  • 1,158
  • 4
  • 15
  • 30
  • 1
    Why are you doing this with `exec`? What is your actual use case? – Chris_Rands Nov 13 '17 at 08:56
  • Possible duplicate of [How do I put a variable inside a String in Python?](https://stackoverflow.com/questions/2960772/how-do-i-put-a-variable-inside-a-string-in-python) – Chris_Rands Nov 13 '17 at 08: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. – bruno desthuilliers Nov 13 '17 at 09:01

1 Answers1

5

Use the format function:

s = "alpha = 'a'"
exec """def my_func({}):
  return alpha""".format(s)
asherbret
  • 5,439
  • 4
  • 38
  • 58