Reasoning behind `from … import …` syntax in Python

后端 未结 8 1541
刺人心
刺人心 2020-12-18 20:35

I always wondered why the syntax for importing specific objects from a module is from module import x, y, z instead of import x, y, z from module.

相关标签:
8条回答
  • 2020-12-18 21:29

    It might make more sense in english to say import x, y, z from module but in programming it makes much more sense to bring the more general Item first and then bring the details. It might not be the reason but it makes things easier for the compiler or interpreter. Try writing a compiler and you'll know what I mean :D

    0 讨论(0)
  • 2020-12-18 21:34

    No idea why it was actually done that way but it's the way I'd do it, simply because, being an engineering type, it seems more natural to me to start from a general category and drill down to specifics.

    It would also mean the parser would have to store less stuff if processing sequentially. With:

    import x, y, z from a
    

    you have to remember x, y and z. With:

    from a import x, y, z
    

    you only have to remember a.


    That's why I had so much trouble when I first encountered Perl's post-if variant:

    $x = $y if $y > 40;
    

    since you don't know in advance whether what you're reading is conditional or not.

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