Skip to content

from sys import path in compile in a local function raises NameError #132271

@lionelkusch

Description

@lionelkusch

Bug report

Bug description:

function = True
if function:
    def run_example():
        code = """
from sys import path
    
def function():
    print(path)
    
function()
        """
        # Compile the code
        compiled_code = compile(code, 'test_function.py', 'exec')

        # Execute the compiled code
        exec(compiled_code)
    run_example()
else:
    # Read the file
    code = """
from sys import path
    
def function():
    print(path)
    
function()
    """
    # Compile the code
    compiled_code = compile(code, 'test_function.py', 'exec')

    # Execute the compiled code
    exec(compiled_code)

When the boolean is true, I get this error:

Traceback (most recent call last):
  File ".../error_import.py", line 17, in <module>
    run_example()
    ~~~~~~~~~~~^^
  File ".../error_import.py", line 16, in run_example
    exec(compiled_code)
    ~~~~^^^^^^^^^^^^^^^
  File "test_function.py", line 7, in <module>
    def function():
    ^^^^^^^^^^
  File "test_function.py", line 5, in function
    from sys import path
              ^^^^
NameError: name 'path' is not defined

If the boolean is false, I didn't get any error.

CPython versions tested on:

3.13

Operating systems tested on:

Linux

Metadata

Metadata

Assignees

No one assigned

    Labels

    interpreter-core(Objects, Python, Grammar, and Parser dirs)type-bugAn unexpected behavior, bug, or error

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions