I already checked if my question was answered elsewhere, but the 2 questions (Can anyone explain python's relative imports? and Python gives relative import error for package?) I found that looked the most as mine did not answer my problem. I also searched using the following search query: "no module named package.module".)
I'm working on a package which should both be usable as tool and be able to be imported by other scripts. So I set it up in the following way:
/<package_name>/__init__.py # to be able to import it by other scripts
/__main__.py # to be able to use it 'live' as tool
/<modules.py>
Originally I had my __main__.py
and my modules set up as pylint wants:
using a "mocked" __main__.py
as example:
import package_name.module1 as module1
import package_name.module2 as module2
def main(arg_list=None):
module1.somefunction()
module2.somefunction()
if __name__ == '__main__':
main()
But when I execute this I get the following error (even in __main__.py
):
No module named package_name.module1
If I remove the package_name
from the imports the execution work, but then pylint starts complaining:
__main__.py: 1: [W0403(relative-import), ] Relative import 'module1', should be 'package_name.module1'
__main__.py: 2: [W0403(relative-import), ] Relative import 'module2', should be 'package_name.module2'
I already tried from package_name import module1
but also then I get the same error when executing the code.
What should I do to fix it so both pylint and the tool execution accept the same code (preferable the import as pylint wants it)?
Edit: Just for clarity: the company I'm working for still uses Python 2.7 at the moment, but we are making the code python 3 compatible by using the Python 3 print-statements and such (from __future__ import <python3 functionality>
).
(Note: __init__.py
only imports __main__.py
and calls main()
and for that no issues are given when I do import package_name.__main__
)