Search code examples
pythonpython-2.7python-2.xpython-module

Automatically import to all Python files in the given folder?


I am relatively quite new to Python and I try to learn the "Pythonic" way of doing things to build a solid foundation in terms of Python development. Perhaps what I want to achieve is not Python at all, but I am nonetheless seeking to find out the "right" way to solve this issue.

I am building an application, for which I am creating modules. I just noticed that a module of mine has 7 different .py Python files, all importing 3 different same things. So all these files share these imports.

I tried removing them, and inserting these import to the empty init.py in the folder, but it did not do the trick.

If possible, since these imports are needed by all these module files, I would not like them to be imported in each file one by one.

What can I do to perform the common import?

Thank you very much, I really appreciate your kind help.


Solution

  • As the Zen of Python states, "Explicit is better than implicit", and this is a good example.

    It's very useful to have the dependencies of a module listed explicitly in the imports and it means that every symbol in a file can be traced to its origin with a simple text search. E.g. if you search for some_identifier in your file, you'll either find a definition in the file, or from some_module import some_identifier. It's even more obvious with direct references to some_module.some_identifier. (This is also one reason why you should not do from module import *.)

    One thing you could do, without losing the above property, is to import your three shared modules into a fourth module:

    #fourth.py
    import first
    import second
    import third
    

    then...

    #another.py
    import fourth
    
    fourth.first.some_function()
    #etc.
    

    If you can't stomach that (it does make calls more verbose, after all) then the duplication of three imports is fine, really.