What benefits or disadvantages would importing a module that contains 'import' commands?

前端 未结 2 477
野趣味
野趣味 2021-01-22 07:31

If I were to create a module that was called for example imp_mod.py and inside it contained all (subjectively used) relevant modules that I frequently used.

相关标签:
2条回答
  • 2021-01-22 07:48

    As lucasnadalutti mentioned, you can access them by importing your module.

    In terms of advantages, it can make your main program care less about where the imports are coming from if the imp_mod handles all imports, however, as your program gets more complex and starts to include more namespaces, this approach can get more messy. You can start to handle a bit of this by using __init__.py within directories to handle imports to do a similar thing, but as things get more complex, personally, I feel it add a little more complexity. I'd rather just know where a module came from to look it up.

    0 讨论(0)
  • 2021-01-22 07:49

    Yes, it would allow you to access them. If you place these imports in imp_mod.py:

    from os import listdir
    from collections import defaultdict
    from copy import deepcopy
    

    Then, you could do this in another file, say, myfile.py:

    import imp_mod
    imp_mod.listdir
    imp_mod.defaultdict
    imp_mod.deepcopy
    

    You're wrong about reduction of importing time, as what happens is the opposite. Python will need to import imp_mod and then import the other modules afterwards, while the first import would not be needed if you were importing these modules in myfile.py itself. If you do the same imports in another file, they will already be in cache, so virtually no time is spent in the next import.

    The real disadvantage here is less readability. Whoever looks at imp_mod.listdir, for example, will ask himself what the heck is this method and why it has the same name as that os module's method. When he had to open imp_mod.py just to find out that it's the same method, well, he probably wouldn't be happy. I wouldn't.

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