[Python] Python: Confusing Scope of `exec`

Discussão em 'Python' iniciado por Stack, Fevereiro 6, 2025.

  1. Stack

    Stack Membro Participativo

    The following code works ok in python

    import numpy as np

    def foo(a):
    b = np.exp(a)
    return b

    c = foo(1)

    print(c)


    Using the code inside an exec, it also works ok, no problem:

    e = "import numpy as np\n\ndef foo(a):\n b = np.exp(a)\n return b\n\nc = foo(1)\n\nprint(c)"
    exec(e)


    Using the code inside a nested function, it also works ok, no problem (now the module is imported inside the function):

    def bar():
    import numpy as np

    def foo(a):
    b = np.exp(a)
    return b

    c = foo(1)

    print(c)

    bar()


    However, when I try to create a function to exec the code inside a string, inside a function, as in the code below, it gives me an error:

    e = "import numpy as np\n\ndef foo(a):\n b = np.exp(a)\n return b\n\nc = foo(1)\n\nprint(c)"

    def baz(s):
    exec(s)

    baz(e)


    Error:

    Traceback (most recent call last):
    File "...\test.py", line 6, in <module>
    baz(e)
    File "...\test.py", line 4, in baz
    exec(s)
    File "<string>", line 7, in <module>
    File "<string>", line 4, in foo
    NameError: name 'np' is not defined


    Why is that?

    Continue reading...

Compartilhe esta Página