go-python / gopy

gopy generates a CPython extension module from a go package.
BSD 3-Clause "New" or "Revised" License
2.05k stars 113 forks source link

Mixed relative and absolute imports #309

Closed mlange-42 closed 1 year ago

mlange-42 commented 1 year ago

When running gopy according to the docs and having multiple packages in the module where one imports the other, relative as well as absolute imports are used. Thereby, it becomes impossible to import the depending package.

Exemplary project structure:

mymod
|-- ecs
|   `-- ecs.go
`-- model
    `-- model.go

Where model imports ecs.

Running this command:

gopy pkg -output=out github.com/mlange-42/mymod

The generated code in model.py looks like this:

# ...

from ..mymod import _mymod
from ..mymod import go

os.chdir(cwd)

# to use this code in your end-user python file, import it as follows:
# from mymod import model
# and then refer to everything using model. prefix
# packages imported by this package listed below:

from mymod import ecs

# ...

Depending on where I start the REPL and how I try to import, I get either:

    from ..mymod import _mymod
ImportError: attempted relative import beyond top-level package

(Run from out, with from mymod import model)

or:

    from mymod import ecs
ModuleNotFoundError: No module named 'mymod'

(Run from mymod, with from out.mymod import model)

Workaround

The only way I could get it to work (without editing generated Python files) is to run gopy with package-prefix set to nothing:

gopy pkg -output=out -package-prefix= github.com/mlange-42/mymod

Then, running the Python REPL from out, it works:

from mymod import model

This is not obvious from the docs, and probably also not intendend. Possibly related to #245, #301, #302

mlange-42 commented 1 year ago

Digging a bit further in the gopy code, I think the imports should look like this when the prefix is not set (i.e. the default "."):

from . import _mymod
from . import go

# ...

from . import ecs