Python: circular imports needed for type checking

后端 未结 4 1292
太阳男子
太阳男子 2021-02-08 02:51

First of all: I do know that there are already many questions and answers to the topic of the circular imports.

The answer is more or less: \"Design your Module/Class s

4条回答
  •  误落风尘
    2021-02-08 03:33

    You can program against interface (ABC - abstract base class in python), and not specific type Bar. This is classical way to resolve package/module inter-dependencies in many languages. Conceptually it should also result in better object model design.

    In your case you would define interface IBar in some other module (or even in module that contains Foo class - depends on the usage of that abc). You code then looks like this:

    foo.py:

    from bar import Bar, IFoo
    
    class Foo(IFoo):
        def __init__(self):
            self.__bar = Bar(self)
    
    # todo: remove this, just sample code
    f = Foo()
    b = Bar(f)
    print f
    print b
    x = Bar('do not fail me please') # this fails
    

    bar.py:

    from abc import ABCMeta
    class IFoo:
        __metaclass__ = ABCMeta
    
    class Bar(object):
        def __init__(self, arg_instance_of_foo):
            if not isinstance(arg_instance_of_foo, IFoo):
                raise TypeError()
    

提交回复
热议问题