Relative Imports

前端 未结 2 948
余生分开走
余生分开走 2021-01-04 05:41

I\'m reading Two Scoops Django Best Practices to make my coding style improve. I\'m in relative imports and here is the sample code to make it reusable.

Old          


        
相关标签:
2条回答
  • 2021-01-04 06:25

    I usually use imports like this only for one reason

    from .foo import bar
    from .other import sample
    

    The reason being If Tomorrow, my module name changes from say 'test' to 'mytest' then the code does not require a refactoring. The code works without breaking.

    Update

    All imports starting with a '.' dot, only works within that package. Cross package imports need require the whole path.

    0 讨论(0)
  • 2021-01-04 06:41

    If test is another app,

    from .other import sample
    

    wont work.

    Update:

    You can only use relative imports when you're importing from the same app.

    Inside test app

    from .other import sample
    

    will work. But you'll still need the complete form

    from cones.foo import bar
    

    if you import method defined in foo from test app.

    So answering your question the second way is the correct way.

    0 讨论(0)
提交回复
热议问题