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

前端 未结 2 552
野趣味
野趣味 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: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.

提交回复
热议问题