Skip to content

"SyntaxError: from __future__ imports must occur at the beginning of the file" after comments #385

@jolaf

Description

@jolaf

Things to check first

  • I have searched the existing issues and didn't find my bug already reported there

  • I have checked that my bug is still present in the latest release

Typeguard version

4.1.2

Python version

3.11.2

What happened?

Traceback (most recent call last):
  File "C:\Temp\test.py", line 4, in <module>
    import_module('A')
  File "C:\Python311\Lib\importlib\__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "<frozen importlib._bootstrap>", line 1206, in _gcd_import
  File "<frozen importlib._bootstrap>", line 1178, in _find_and_load
  File "<frozen importlib._bootstrap>", line 1149, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 690, in _load_unlocked
  File "C:\Python311\Lib\site-packages\typeguard\_importhook.py", line 98, in exec_module
    super().exec_module(module)
  File "<frozen importlib._bootstrap_external>", line 936, in exec_module
  File "<frozen importlib._bootstrap_external>", line 1074, in get_code
  File "C:\Python311\Lib\site-packages\typeguard\_importhook.py", line 87, in source_to_code
    return _call_with_frames_removed(
           ^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Python311\Lib\site-packages\typeguard\_importhook.py", line 47, in _call_with_frames_removed
    return f(*args, **kwargs)
           ^^^^^^^^^^^^^^^^^^
  File "C:\Temp\A.py", line 4
    from __future__ import annotations
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
SyntaxError: from __future__ imports must occur at the beginning of the file

How can we reproduce the bug?

test.py:

from importlib import import_module
from typeguard import install_import_hook
with install_import_hook(('A',)):
    import_module('A')

A.py:

#
# Comment
#
from __future__ import annotations

def f() -> int:
    return 5

print("OK")

Run:

$ python3 A.py
OK

$ python3 test.py
<crash>

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions