1

I found similar discussion here. But my problem is it works running python code in normal mode. When I run in debugging as python -m pdb nmt.py, I have ImportError: attempted relative import with no known parent package. My python version is Python 3.7.13. Error is coming from the following line.

from . import inference

How to make it work in debugging?

batuman
  • 7,066
  • 26
  • 107
  • 229

1 Answers1

2

Explanations

The error message is actually pretty explicit:

Relatives import (using from . import module, or from .module import something) Only work if the module (ie the file) you are editing, and the module you are importing are in the same python package.

That means you need a __init__.py file in that directory (for it to be considered a package).

I recommend you read the documentation on modules if you want to understand the import system better

Quick fixes

  • either add a __init__.py to make your directory into a package
  • or change your relative import to a normal import (ie. change from . import inference to import inference.) — you may need to add the directory containing your files to sys.path (documentation)
tbrugere
  • 755
  • 7
  • 17
  • I have __init__.py in folder. I can run with no error when I use `python -m nmt.nmt --src=vi --tgt=en`. But I have that when I run `python -m pdb nmt/nmt.py --src=vi --tgt=en`. What is the difference? – batuman Jul 11 '22 at 07:46
  • oh the command you use is wrong. It should be `python -m pdb -m nmt.nmt` – tbrugere Jul 11 '22 at 09:59
  • Just think of it as "`python -m pdb` replaces `python`" in your command – tbrugere Jul 11 '22 at 10:01
  • Yes that is the one `python -m pdb -m nmt.nmt` – batuman Jul 11 '22 at 11:25
  • the difference is that `-m` runs your module as a module, whether the other one runs it as a standalone script – tbrugere Jul 11 '22 at 13:44