importing the module in python
Question: I am learning Python and while studying modules two doubts came to my mind.

  * **Doubt #1:**

I know that module is just simply python file such as `filename.py`, but what
is a sub-module in Python?

  * **Doubt #2:**

Consider the following three lines of code:

    
        import modulename
    from pkgname import modulename
    from pkgname import *
    

Do all three statements use `__init__.py` (which is inside `pkgname` package)
or only the third statement?


Answer: To make things a bit more clearer about your second question.

* * *

When you do -

    
    
    import packagename.modulename
    

or

    
    
    from packagename import modulename
    

Python internally first imports `packagename` , and when I say python imports
`packagename` , I mean it imports the `__init__.py` of that package , and then
after that it imports `modulename` . This is the reason why when you do any of
the above it imports the `__init__.py` .

* * *

When you do -

    
    
    from packagename import *
    

Please note, this does not import `modulename` from packagename by default ,
this would only import the `__init__.py` from packagename , and all modules
that you have listed in `__all__` list in `__init__.py` , if no modules are
listed in that list, none would be imported. Example -

Lets say I have

    
    
    shared
       -- __init__.py
       -- a.py
    

`__init__.py` looks like -

    
    
    print("In Shared")
    

`a.py` look like -

    
    
    print("In A")
    

Now when in the directory above `shared` ,and openning python, if you do -

    
    
    from shared import *
    

It would print out -

    
    
    In Shared
    

But if you change that code in `__init__.py` to -

    
    
    print("In Shared")
    __all__ = ['a']
    

And do the same import from same location, It would print out -

    
    
    In Shared
    In A
    

As you can see it only imports submodules that are defined in the `__all__`
list.

* * *

Finally , when you do -

    
    
    import modulename
    

Lets say you do that directly from within `packagename` , by changing the
directory to it and openning python interactive interpreter there. At that
time, you are not asking Python to import packagename for you, so it does not
need to import packagename , and hence it does not import `__init__.py` .

