Relative import problems in Python 3

后端 未结 7 1023
庸人自扰
庸人自扰 2021-02-13 21:01

Python imports drive me crazy (my experience with python imports sometime doesn\'t correspond at all to idiom \'Explicit is better than implicit\' :( ):

[app]
           


        
7条回答
  •  Happy的楠姐
    2021-02-13 21:37

    I ran into this same issue today, and it seems this is indeed broken in python3.4, but works in python3.5.

    The changelog has an entry:

    Circular imports involving relative imports are now supported. (Contributed by Brett Cannon and Antoine Pitrou in bpo-17636).

    Looking through the bugreport, it seems that this not so much a buf fixed, as well as a new feature in the way imports work. Referring to poke's answer above, he shows that from . import foo means to load __init__.py and get foo from it (possibly from the implicitly loaded list of submodules). Since python3.5, from . import foo will do the same, but if foo is not available as an attribute, it will fall back to looking through the lists of loaded modules (sys.modules) to see if it is already present there, which fixes this particular case. I'm not 100% sure I properly presented how this works, though.

提交回复
热议问题