Skip to content

imports fail in an exec with empty directory for globals #129004

Closed as not planned
@killermouse0

Description

@killermouse0

Bug report

Bug description:

I can't find out why the following code fails:

(.venv) ➜  git:(master) ✗ python
Python 3.12.3 (main, Nov  6 2024, 18:32:19) [GCC 13.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> exec("""
... import requests
... 
... def get_bitcoin_price():
...     url = "https://api.coingecko.com/api/v3/simple/price?ids=bitcoin&vs_currencies=usd"
...     response = requests.get(url)
...     data = response.json()
...     return data['bitcoin']['usd']
... 
... current_price = get_bitcoin_price()
... print(current_price)
... """, {}, {})
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 10, in <module>
  File "<string>", line 6, in get_bitcoin_price
NameError: name 'requests' is not defined
>>> 

While this one works:

(.venv) ➜  git:(master) ✗ python
Python 3.12.3 (main, Nov  6 2024, 18:32:19) [GCC 13.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> exec("""
... def get_bitcoin_price():
...     import requests
...     url = "https://api.coingecko.com/api/v3/simple/price?ids=bitcoin&vs_currencies=usd"
...     response = requests.get(url)
...     data = response.json()
...     return data['bitcoin']['usd']
... 
... current_price = get_bitcoin_price()
... print(current_price)
... """, {}, {})
103873
>>> 

Could someone more knowledgeable shed some light? It seems to me like it's a bug, but I'm a novice with using exec.

CPython versions tested on:

3.12

Operating systems tested on:

Linux

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions