KungFuPanda
KungFuPanda

Reputation: 57

How to import from a sibling's subdirectory using python

- folder container
     - folder build
         - build.py

     - folder uni
         - folder build-server
             - RemoteInterface.py

Question: How do I import RemoteInterface from build.py? Given that folders "build" and "build-server" do not have an init.py

I tried -

from ..uni.build_server.RemoteInterface import RemoteInterface 

# - shows  attempted relative import beyond top-level package
from ..uni.build-server.RemoteInterface import RemoteInterface 

#- shows syntax error at build-server (for the hyphen)

Shows similar errors for these as well:

from ...uni.build_server.RemoteInterface import RemoteInterface 


from ...uni.build-server.RemoteInterface import RemoteInterface 

Expect successful import of RemoteInterface from build.py

Upvotes: 0

Views: 51

Answers (1)

sunnky
sunnky

Reputation: 175

the directory tree:

.
├── build
│   └── build.py
└── uni
    ├── build-server
    │   └── RemoteInterface.py
    └── buildserver
        └── RemoteInterface.py
  1. uni/build-server/RemoteInterface.py
RemoteInterface = "build-server"
  1. uni/buildserver/RemoteInterface.py
RemoteInterface = "buildserver"
  1. build/build.py
from __future__ import absolute_import
import sys
from os import path
sys.path.append(path.dirname(path.dirname(path.abspath(__file__))))
from importlib import import_module
from uni.buildserver import RemoteInterface


import_module("uni.build-server.RemoteInterface")
_RemoteInterface = sys.modules["uni.build-server.RemoteInterface"]

print(RemoteInterface.RemoteInterface)
print(_RemoteInterface.RemoteInterface)
  1. output:
buildserver
build-server

Note: try not to appear in the directory name -

Upvotes: 1

Related Questions