Skip to content

Commit

Permalink
Merge pull request #531 from pypa/i530
Browse files Browse the repository at this point in the history
Fix relative imports in __init__.py when exec-ing to get __version__
  • Loading branch information
takluyver committed Feb 23, 2022
2 parents bdafdfe + b361f4b commit a6e9501
Show file tree
Hide file tree
Showing 6 changed files with 35 additions and 1 deletion.
6 changes: 6 additions & 0 deletions doc/history.rst
Original file line number Diff line number Diff line change
@@ -1,6 +1,12 @@
Release history
===============

Version 3.7.1
-------------

- Fix building packages which need execution to get the version number,
and have a relative import in ``__init__.py`` (:ghpull:`531`).

Version 3.7
-----------

Expand Down
11 changes: 10 additions & 1 deletion flit_core/flit_core/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import hashlib
import logging
import os
import sys

from pathlib import Path
import re
Expand Down Expand Up @@ -168,7 +169,15 @@ def get_docstring_and_version_via_import(target):
spec = spec_from_file_location(mod_name, target.file)
with _module_load_ctx():
m = module_from_spec(spec)
spec.loader.exec_module(m)
# Add the module to sys.modules to allow relative imports to work.
# importlib has more code around this to handle the case where two
# threads are trying to load the same module at the same time, but Flit
# should always be running a single thread, so we won't duplicate that.
sys.modules[mod_name] = m
try:
spec.loader.exec_module(m)
finally:
sys.modules.pop(mod_name, None)

docstring = m.__dict__.get('__doc__', None)
version = m.__dict__.get('__version__', None)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
"""This module has a __version__ that requires a relative import"""

from ._version import __version__
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
__version__ = '0.5.8'
10 changes: 10 additions & 0 deletions flit_core/flit_core/tests/samples/imported_version/pyproject.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
[build-system]
requires = ["flit_core >=3.2,<4"]
build-backend = "flit_core.buildapi"

[project]
name = "package1"
authors = [
{name = "Sir Röbin", email = "robin@camelot.uk"}
]
dynamic = ["version", "description"]
5 changes: 5 additions & 0 deletions flit_core/flit_core/tests/test_common.py
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,11 @@ def test_get_info_from_module(self):
'version': '1.2.3'}
)

info = get_info_from_module(Module('package1', samples_dir / 'imported_version'))
self.assertEqual(info, {'summary': 'This module has a __version__ that requires a relative import',
'version': '0.5.8'}
)

with self.assertRaises(InvalidVersion):
get_info_from_module(Module('invalid_version1', samples_dir))

Expand Down

0 comments on commit a6e9501

Please sign in to comment.