python namespace: __main__.Class not isinstance of package.Class

前端 未结 3 2100
轮回少年
轮回少年 2021-01-12 08:41

Consider you have two python files as defined below. Say one is a general package (class2), and the other one does specific overrides and serves as the executab

3条回答
  •  逝去的感伤
    2021-01-12 09:13

    If you plan to import class1.py from elsewhere, move the top-level code (if __name__ == '__main__': ... to a separate file altogether. That way both the main file and class2 work with the same class1.Test class.

    Doing almost anything else opens a can of worms. While you can work around the immediate problem by switching isinstance to type(myObject).__name__ == ..., the fact remains that your Python process contains two Test classes where there should be only one. The otherwise indistinguishable classes know nothing of each other and fail each other's issubclass tests. This practically guarantees hard-to-diagnose bugs further down the line.

    EDIT
    Another option is to explicitly import the classes from class1 when executing as main, as in your answer. It would be advisable to go one step further and make sure that the classes aren't defined in double. For example, you can move the if __name__ == '__main__' block to the beginning of the file, and end it with sys.exit(0):

    if __name__ == '__main__':
        import class1, class2
        ... use only the public API with module prefixes ...
        sys.exit(0)
    
    # the rest of the module follows here
    

提交回复
热议问题