1
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'

Bogota
  • 401
  • 4
  • 15
  • https://stackoverflow.com/questions/24733831/using-a-function-defined-in-an-execed-string-in-python-3 This helped me a huge amount, I just took a while to find it – AlltheAce494 May 21 '20 at 10:54

0 Answers0