Skip to content

fix relative imports

Sebastian Steinlechner requested to merge et-pathfinder/pygwinc:master into master

Closely related to #45 (closed).

Consider the following setup:

MyIFO
|- __init__.py
|- ifo.yaml
\- something.py

where ifo.yaml can just be copied from e.g. ALigo. __init__.py looks like this:

from gwinc.ifo.noises import *
from . import something

class MyIFO(nb.Budget):
    name = 'MyIFO'
    noises = [
        QuantumVacuum,
    ] 

and something.py is just

def test():
    pass

Then, when in the directory immediately above MyIFO, executing gwinc MyIFO works as expected. However, moving one directory further up or sideways, so that a relative path becomes necessary (i.e. gwinc path/to/MyIFO), this happens:

Traceback (most recent call last):
  File "/usr/local/bin/gwinc", line 11, in <module>
    load_entry_point('pygwinc', 'console_scripts', 'gwinc')()
  File "/Users/sebastian/work/repos/coding/pygwinc/gwinc/__main__.py", line 100, in main
    Budget = load_budget(args.IFO)
  File "/Users/sebastian/work/repos/coding/pygwinc/gwinc/__init__.py", line 84, in load_budget
    mod, modpath = _load_module(modname)
  File "/Users/sebastian/work/repos/coding/pygwinc/gwinc/__init__.py", line 27, in _load_module
    spec.loader.exec_module(mod)
  File "<frozen importlib._bootstrap_external>", line 728, in exec_module
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "simulations/MyIFO/__init__.py", line 2, in <module>
    from . import something
ModuleNotFoundError: No module named 'MyIFO'

This merge request fixes this by explicitly adding the module to sys.modules in pygwinc's _load_module():

mod = importlib.util.module_from_spec(spec)
sys.modules[mod] = mod     ### this line here, with matching "import sys" above
spec.loader.exec_module(mod)

See Python3 doc, which was apparently changed relatively recently to add exactly this line.

Edited by Sebastian Steinlechner

Merge request reports

Loading