isinstance return improper result with nested application

58 views Asked by At

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.

1

There are 1 answers

3
Antti Haapala -- Слава Україні On BEST ANSWER

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__.