0
>>> def create_function(code):
...     exec(code)
...
>>>
>>>
>>> def main():
...     code = "def a(stri):\n\tprint(stri)"
...     create_function(code)
...     a("Hello World")
...
>>> main()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 4, in main
NameError: name 'a' is not defined
>>>

I want to do this for Discord.py Embeds, Is there way to define function with exec command in another function ?

1 Answers1

0

This is a terrible way to do this. But if you really want to do this, you have to make the function global.

def create_function(code):
    exec(code)


def main():
    code = "global a\ndef a(stri):\n\tprint(stri)"
    create_function(code)
    a("Hello World")

main()
KetZoomer
  • 2,701
  • 3
  • 15
  • 43
  • you don't *have* to and it's probably not recommended to, rather, you. should explicitly pass a namespace and extract it from there – juanpa.arrivillaga Jul 28 '21 at 15:17
  • It works fine! Do you recommend another way to do this ? User will input code and i will run it. Code looks like this ```embed=discord.Embed() embed.add_field(name="undefined", value="undefined", inline=False) await ctx.send(embed=embed)``` – Yusuf Can İlbeyli Jul 28 '21 at 15:19
  • @YusufCanİlbeyli you should never trust users to run code, but if you are, I can't of a better way to do this. If you can (not sure how your code look) you might be able to bypass the function that creates the code and/or the function that contains the code. Also, if this answer helped you, please click on the checkmark – KetZoomer Jul 28 '21 at 15:21
  • Understood, I'm new to Stackoverflow so i can't – Yusuf Can İlbeyli Jul 28 '21 at 15:26