0

I am new to python packages and currently using tox with pyscaffold to prepare packages.

The structure of my code directory is as follows:

-- project
-- src
----__init__.py
---- data_prep.py
---- modelling.py
---- main.py

Now when i build package with tox -e build, i need to call the modelling.py inside main.py with following signature

from . import modelling

But when i am trying to execute it standalone by just introducing main in main.py class in bottom.That time, this kind of import not works and i have to change above import to

import modelling

How can I modify this import statement so that it suffices both cases.Kindly help.

init.py

import sys

if sys.version_info[:2] >= (3, 8):
    # TODO: Import directly (no need for conditional) when `python_requires = >= 3.8`
    from importlib.metadata import PackageNotFoundError, version  # pragma: no cover
else:
    from importlib_metadata import PackageNotFoundError, version  # pragma: no cover

try:
    # Change here if project is renamed and does not equal the package name
    dist_name = "fqr"
    __version__ = version(dist_name)
except PackageNotFoundError:  # pragma: no cover
    __version__ = "unknown"
finally:
    del version, PackageNotFoundError

main.py(for standalone purposes)

def main():
   ##relevant code lines

if __name__=="__main__":
  main()
Arshanvit
  • 417
  • 1
  • 7
  • 28
  • Can you please show the relevant section of the `main.py` file that is used when run as standalone? – 9769953 Aug 30 '22 at 08:50
  • Note that if `src` is a package (judging from your first import example), then you might want to rename the directory to the package name, or add the files in a subdirectory of `src`, with the subdirectory being the package name. This is perhaps not fully necessary, but can make things a lot easier. – 9769953 Aug 30 '22 at 08:53
  • How are you running `main.py` as standalone? – 9769953 Aug 30 '22 at 08:54
  • Would help to see your tox file to know what your `build` env is doing. Generally, I use absolute imports to avoid ambiguity and install my package in editable mode – CodeCaffeinateContinue Aug 30 '22 at 08:56
  • maybe you should use `if __name__=="__main__":` to run different imports. something like `if __name__=="__main__": import modelling else: from . import modelling` – furas Aug 30 '22 at 10:22

0 Answers0