1

Lets say we have two python files:

A:

class c(object):pass

def f(obj):
        if type(obj) == c:
                print("Object is of type c!")
        else:
                print("Object is not of type c.")
                print(f"Type c: {c}")
                print(f"Type of the object: {type(obj)}")

o = c()

B:

import A

o = A.c()

Now lets run A in shell or using the -i arguments in a command line, import B and call f using the object we created in B as an argument.

>>> import B
>>> f(B.o)
Object is not of type c.
Type c: <class '__main__.c'>
Type of the object: <class 'A.c'>

Can I some how fix this?

Just to clarify: I do want to execute a program like A and then import a program like B. I just want to know if I can somehow make f work in this context.

Minek Po1
  • 142
  • 1
  • 9
  • 1
    Does `isinstance(B.o, A.c)` give different results? – Random Davis Nov 25 '20 at 16:10
  • Since the problem seems to be the inclusion of the `__main__` in the class type, after a quick google for *"python type \__main\__"* [this](https://stackoverflow.com/q/54018653/9063935) and [this](https://stackoverflow.com/a/48846044/9063935) came back – dwb Nov 25 '20 at 16:16

1 Answers1

1

Ok, I think I've cracked it.

When you run

python -i A.py

this is the same as copying each line from A.py into an interactive python shell. This shell is it's own environment, you are not editing or 'extending' A.py. Incidentally the name of this environment is __main__.

In other words, python -i A.py creates a new class c different from A.c even though the two classes are identical in functionality. When you then import B, this imports from A.py, ie the 'old' class A.c.