Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use absolute and relative imports in python 3.6?

I have a python project/library called "slingshot" with the following directory structure:

slingshot/
    __init__.py
    __main__.py
    build.py
    deploy.py
    util/
        __init__.py
        prepare_env.py
        cdn_api.py

From __main__.py I would like to import functions from util/prepare_env.py.

I would like to ensure that util refers to the util I have in my project, and not some other util library that may be installed somewhere.

I tried from .util import prepare_env but I get an error.

from util import prepare_env seems to work, but doesn't address the ambiguity of "util".

What am I doing wrong?


__main__.py is as follows:

import os
from .util import prepare_env

if __name__ == '__main__':
    if 'SLINGSHOT_INITIALIZED' not in os.environ:
        prepare_env.pip_install_requirements()
        prepare_env.stub_travis()
        prepare_env.align_branches()
        os.environ['SLINGSHOT_INITIALIZED'] = 'true'

When I type python3 ./slingshot I get the following error:

  File "./slingshot/__main__.py", line 2, in <module>
    from .util import prepare_env
ImportError: attempted relative import with no known parent package

When I type python3 -m ./slingshot I get the following error:

/usr/local/opt/python3/bin/python3.6: Relative module names not supported
like image 535
tadasajon Avatar asked Dec 01 '17 17:12

tadasajon


1 Answers

__main__.py modules in a package make the module run as a script when you use the -m command line switch. That switch takes a module name, not a path, so drop the ./ prefix:

python3 -m slingshot

The current working directory is added to the start of the module search path so slingshot is found first, no need to give a relative path specification here.

From the -m switch documentation:

Search sys.path for the named module and execute its contents as the __main__ module.

Since the argument is a module name, you must not give a file extension (.py). The module name should be a valid absolute Python module name[.]

[...]

As with the -c option, the current directory will be added to the start of sys.path.

like image 171
Martijn Pieters Avatar answered Nov 14 '22 21:11

Martijn Pieters