Skip to content

warn_explicit() issues a warning or an error when used directly in a script #123011

Open
@serhiy-storchaka

Description

@serhiy-storchaka

For example, running the following script:

import warnings
warnings.warn_explicit('eggs', UserWarning, 'bar', 1, module_globals=globals())

emits a warning:

$ ./python t.py
<frozen importlib._bootstrap_external>:932: DeprecationWarning: Module globals is missing a __spec__.loader
/home/serhiy/py/cpython3.13/t.py:1: UserWarning: eggs
  import warnings

Running it as a module produces an error:

$ ./python -m t
Traceback (most recent call last):
  File "/home/serhiy/py/cpython3.13/Lib/runpy.py", line 198, in _run_module_as_main
    return _run_code(code, main_globals, None,
                     "__main__", mod_spec)
  File "/home/serhiy/py/cpython3.13/Lib/runpy.py", line 88, in _run_code
    exec(code, run_globals)
    ~~~~^^^^^^^^^^^^^^^^^^^
  File "/home/serhiy/py/cpython3.13/t.py", line 2, in <module>
    warnings.warn_explicit('eggs', UserWarning, __file__, 1, module_globals=globals())
    ~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "<frozen importlib._bootstrap_external>", line 1073, in get_source
  File "<frozen importlib._bootstrap_external>", line 674, in _check_name_wrapper
ImportError: loader for t cannot handle __main__

Running it in the REPL produces similar error:

>>> import warnings
... warnings.warn_explicit('eggs', UserWarning, 'bar', 1, module_globals=globals())
... 
Traceback (most recent call last):
  File "<python-input-0>", line 2, in <module>
    warnings.warn_explicit('eggs', UserWarning, 'bar', 1, module_globals=globals())
    ~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "<frozen importlib._bootstrap_external>", line 1073, in get_source
  File "<frozen importlib._bootstrap_external>", line 674, in _check_name_wrapper
ImportError: loader for _pyrepl.__main__ cannot handle __main__

But importing it as a module is OK:

>>> import t
/home/serhiy/py/cpython3.13/t.py:1: UserWarning: eggs
  import warnings

The warning was introduced in #86298, but I think that it was for modules created in non-standard way. Running Python code as a script is pretty standard, this is not a user error. We should handle this case specially.

cc @brettcannon, @warsaw

Metadata

Metadata

Assignees

No one assigned

    Labels

    type-bugAn unexpected behavior, bug, or error

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions