0

Related to: Import a module from a relative path

dirA/
    A.py
    B.py
dirB/
    B.py

A.py
import B

# do blah

I want A to import B.

How do i specify A to import B from dirB instead of dirA since both dirs have B.py?

Community
  • 1
  • 1
ealeon
  • 12,074
  • 24
  • 92
  • 173
  • What do you mean by "I want A to import B". There are two Bs. Which B do you want A to import? Why do you have `B.py` in `dirA` if you don't want A to import it? – BrenBarn Feb 05 '15 at 20:10
  • exactly. thats the problem since there are two. Its a version control thing in my software. there are cases where A (which is a wrapper) needs import from previous version B.py located in different tree in the file system – ealeon Feb 05 '15 at 20:11
  • 2
    I think you should explain your actual situation. You probably need to rethink your strategy for this problem. Trying to import one of multiple identically-named files in separate directories that are not packages is going to lead to very confusing code. – BrenBarn Feb 05 '15 at 20:18

3 Answers3

6

I think what you're asking for is how to load a module directly from a directory.

import imp

moduleB = imp.load_source('moduleB', '/ModuleBPath/B.py')
moduleB.MyClass()
Jeremy Sayers
  • 637
  • 4
  • 10
  • 23
2

u can use like below :-

from A import B
from B import B as B1

and continue to use.

vijay
  • 679
  • 2
  • 7
  • 15
  • i think this is assumping that dirA and dirB has __init__.py. what if they dont? – ealeon Feb 05 '15 at 20:15
  • Please refer this stack overflow link for your question >> http://stackoverflow.com/questions/5910379/importing-modules-in-python-and-init-py – vijay Feb 06 '15 at 04:59
1

You could try such variant:

from ..dirB import B
renskiy
  • 1,330
  • 1
  • 13
  • 12