pythonpython-importrelative-import

How to import entire own module in Python as an alias?


I have a directory structure like the following:

my-package/
    config/
        __init__.py
        constants.py
        logging.py
    app.py

From within config/__init__.py, I'd like to do an import along the lines of:

import .constants as const

or

from .constants import * as const

But of course neither syntax is valid.

Just wanted to ask if anyone has any ideas on how to achieve this.

I looked through several other related SO posts, and none of them seem to address this specific case.


Solution

  • You want:

    from . import constants as const
    

    which means "from the current package level (.), import constants and alias it as const.