[Python] Using a function defined in an exec'ed string in Python 3 [duplicate]

Discussão em 'Python' iniciado por Stack, Julho 8, 2025.

  1. Stack

    Stack Membro Participativo

    Why does the following python3 code produces an error?

    a='''
    def x():
    print(42)
    '''

    class Test:
    def __init__(self):
    exec(a)
    x()

    t = Test()


    Results in this message:

    Traceback (most recent call last):
    File "bug.py", line 11, in <module>
    t = Test()
    File "bug.py", line 9, in __init__
    x()
    NameError: global name 'x' is not defined

    Continue reading...

Compartilhe esta Página