python-3.ximportpackage

How can I import a package from a inside the same package?


I know this has been discussed many times.. however, I've read many, many answers here that did not show my specific use case, and all I would like is an answer that's suitable for this very case. I love Python (most of it), but the import system is IMHO an absolute mess and very, very quirky and tricky to use.

I am developing a package, and I'd like to have a showcase.py module inside of it which demonstrates the use of the package in the exact same manner and syntax that a user would use it from outside the package.

some_dir/package/__init__.py
                 showcase.py

If a user imports my package from a module located in some_dir, he can write import package and use it. Now I'd would like to have this exact same import syntax in my showcase.py module. I tried like many many things, but I cannot get it working. I am fine to amend sys.path if needed, I'd just like to know how to solve this one single problem.


Solution

  • This is the basic idea. Let me assume that this is the directory structure.

    grandparent_folder/
    ├── gp.py
    ├── parent_folder/
    │   ├── __init__.py
    │   ├── parent.py
    │   └── child_folder/
    │       ├── __init__.py
    │       ├── child.py
    

    Now let us see how the other two python packages to be imported in each python script

    In gp.py:

    from parent_folder import parent  # Import parent.py
    from parent_folder.child_folder import child  # Import child.py
    

    In parent.py:

    import sys
    from pathlib import Path
    
    # Add grandparent_folder to sys.path
    sys.path.append(str(Path(__file__).resolve().parent.parent))
    
    import gp  # Import gp.py from grandparent_folder
    from parent_folder.child_folder import child  # Import child.py
    

    In child.py:

    import sys
    from pathlib import Path
    
    # Add grandparent_folder to sys.path
    sys.path.append(str(Path(__file__).resolve().parent.parent.parent))
    
    import gp  # Import gp.py from grandparent_folder
    from parent_folder import parent  # Import parent.py