推荐学习书目
› Learn Python the Hard Way
Python Sites
› PyPI - Python Package Index
› http://diveintopython.org/toc/index.html
› Pocoo
值得关注的项目
› PyPy
› Celery
› Jinja2
› Read the Docs
› gevent
› pyenv
› virtualenv
› Stackless Python
› Beautiful Soup
› 结巴中文分词
› Green Unicorn
› Sentry
› Shovel
› Pyflakes
› pytest
Python 编程
› pep8 Checker
Styles
› PEP 8
› Google Python Style Guide
› Code Style from The Hitchhiker's Guide
911061873
V2EX  ›  Python

Python 重复导入的问题

  •  
  •   911061873 · Sep 17, 2021 · 3337 views
    This topic created in 1887 days ago, the information mentioned may be changed or developed.

    项目目录如下

    │ a.py
    └─api
    	b.py
    	__init__.py
    

    a 中的内容

    from api.b import test
    aaa = 'a'
    test()
    

    b 中的内容

    from a import aaa
    def test():
        print(aaa)
    

    现在执行 a 就提示导入重复。不知道怎么解决

    11 replies  •  2021-09-22 09:47:55 +08:00
    yunyuyuan
    yunyuyuan
    Sep 17, 2021
    1
    a 改成
    ```python
    aaa = 'a'
    from api.b import test
    test()
    ```
    911061873
    911061873
    OP
    Sep 17, 2021
    2
    @yunyuyuan 如果只是换了下位置 我试了下好像还是不行
    zhuangzhuang1988
    zhuangzhuang1988
    Sep 17, 2021
    3
    看下 <effective python>
    第 88 条 用适当的方式打破循环依赖关系 // 350
    https://book.douban.com/subject/35334595/
    LicenseXu
    LicenseXu
    Sep 17, 2021
    4
    b.py 里的 import 放到函数 test 里面
    def test():
    from a import aaa
    print(aaa)
    yunyuyuan
    yunyuyuan
    Sep 17, 2021
    5
    @911061873 搞忘了,要加 main 的,这样就行了。

    aaa = 'aaa'

    if __name__ == '__main__':
    from api.b import test
    test()
    yunyuyuan
    yunyuyuan
    Sep 17, 2021
    6
    v 站到底怎么发代码
    2owe
    2owe
    Sep 17, 2021
    7
    增加 c,将 aaa 移到 c 中,让 c 可以被其它引用
    Nich0la5
    Nich0la5
    Sep 17, 2021
    8
    这不是循环依赖吗 不要这么搞
    jaredyam
    jaredyam
    Sep 17, 2021
    9
    竟然还能从 b 里导入 a,就很神奇
    jaredyam
    jaredyam
    Sep 17, 2021
    10
    你这种写法还会出很多其它问题,里包导外包应该使用相对导入,from ..a import ...
    frostming
    frostming
    Sep 22, 2021
    11
    def test():
    from a import aaa
    print(aaa)

    把 import 移到 test 里面去就解决问题了
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   4727 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 41ms · UTC 01:43 · PVG 09:43 · LAX 17:43 · JFK 20:43
    ♥ Do have faith in what you're doing.