def square(n):
def func(): pass
s = 'def func(x): return x**2'
exec(s)
return func(n)
print(square(2))
In this code the exec(s)
line does not run so the func isn't defined I get:
TypeError: func() takes 0 positional arguments but 1 was given
Thats because the dummy function is running and not being overwritten
But if I run
def square(n):
def func(): pass
def func(x): return x**2
return func(n)
print(square(2))
It outputs correctly
Further if I run:
def func(): pass
s = 'def func(x): return x**2'
exec(s)
print(func(2))
I get out the correct output so function can be defined using 'exec'
Any comments on how to fix the first error and define a function within a function using 'exec'