0

I developed a tool and I want to use it in another application. Now, I just copy my tool in the new application. The file architecture is shown as below.

.
├── inner
│   ├── a
│   │   ├── a.py
│   │   └── __init__.py
│   ├── b
│   │   ├── b.py
│   │   └── __init__.py
│   ├── __init__.py
│   └── inner.py
└── outer.py

a.py

class A(object):

    def output(self):
        print('A')

b.py

from a.a import A


class B(object):

    def output(self, a):
        print('B')
        print(isinstance(a, A))

inner.py

from a.a import A
from b.b import B

a = A()
b = B()
a.output()
b.output(a)

B.output will check whether the second argument a is an instance of class A. Running inner.py under folder inner gives the output

A
B
True

However, when I run almost the same code outer.py under my new application folder, the output is not expected.

A
B
False

outer.py

import sys

sys.path.append('inner')


if __name__ == '__main__':
    from inner.a.a import A
    from inner.b.b import B
    a = A()
    b = B()
    a.output()
    b.output(a)

When I add print(a) in outer.py, I get <inner.a.a.A object at 0x7f45e179f2d0>, not a.a.A object.

I wonder, how to integrate the inner application to make isinstance return a proper result? Shall I add all the folders under inner into sys.path? If so, I will choose to remove the type detection.

Ben Lee
  • 102
  • 1
  • 1
  • 9

1 Answers1

0

This does get asked from time to time but I couldn't find a proper duplicate.

Instead of running scripts within packages, make it into an installable Python package that you will install, and use python -m inner.inner to run the given module as __main__.

  • A good idea I have never known before! However, I have to change the first line of `inner/b/b.py` with `from inner.a.a import A` to run `inner.py`. Is it the only way to specify the tool name at the very beginning? – Ben Lee Sep 16 '17 at 08:10
  • @AnttiHaapala this sound interesting; can you share an example? I'm trying to better understand your suggestion – Chen A. Sep 16 '17 at 10:43
  • I almost forgot this question... I gave up detecting the type. While developing, import packages with relative path, thus, it's not necessary to use the tool name. Thanks! – Ben Lee Aug 09 '18 at 09:20