-1

I would like to define a function within a function, and call it from out of the function. Here is a simplified version of my code:

def make_func():
    exec('def test(text):\n\tprint(text)')


make_func()
test("Hello")

When I run this code, I get this error:

Traceback (most recent call last):
line 6, in <module>
    test("Hello")
NameError: name 'test' is not defined

Thank you in advance for your help.

SomeMosa
  • 413
  • 5
  • 28
  • 2
    why would you want to do that? i think test is defined only in the scope of the exec – DanielM Aug 18 '19 at 19:18
  • Do you have a suggestion for another function I can use? – SomeMosa Aug 18 '19 at 19:20
  • What's the point? What purpose are you trying to achieve, that you couldn't achieve by defining functions the normal way? (And why did you bring `exec` into this?) – user2357112 Aug 18 '19 at 19:36
  • This is a simplified version of my actual code, in which I have to dynamically create a function from within a function. I don't NEED to use `exec()`, but I can't think of another way to do this – SomeMosa Aug 18 '19 at 19:41

2 Answers2

1

Revision:

You need to add test to the global namescape. Here is the solution:

def make_func():
    exec('def test(text):\n\tprint(text)', globals())


make_func()
test("Hello")

NOTE: This has been asked before.


Previous:

See Python exec(). You cannot call text("Hello) because text() has fallen out-of-scope and is no longer defined. It's only defined within the scope of exec().

However, you could do this:

def make_func():
    exec('def test(text):\n\tprint(text)\ntest("Hello")')


make_func()

Or:

def make_func(text):
    exec('def test(text):\n\tprint(text)\ntest(text)')


make_func("Hello")

Hope that helps.

Matthew E. Miller
  • 557
  • 1
  • 5
  • 13
0

test function is defined inside the make_func function and thus is local to it, to make it global (reachable from anywhere in the code) use (for Python 2.7):

def make_func():
    exec('def test(text):\n\tprint(text)')
    globals()['test'] = test

make_func()
test("Hello")  #  ==>  Hello

For Python 3.x:

def make_func():
    exec('def test(text):\n\tprint(text)', globals())

make_func()
test("Hello")  #  ==>  Hello
DjaouadNM
  • 22,013
  • 4
  • 33
  • 55