How to write __init__.py (and perhaps __main__.py) file to avoid import ModuleNotFoundError

By default the import searches for module on the paths present in sys.path and one of the path present there is of current directory so
when you executed the main script:

python myapp/myapp.py

The import in myapp.py file searched for lib module in its current directory i.e "myapp" and as lib.py is in same directory, it executed perfectly

But when you imported myapp as a package in IPython,
The import in myapp.py file searches from IPython's path, where Lib.py is not present hence the classic no module found.

There are few things you can do here

  1. use relevant path in myapp.py like

    from . import lib
    Note: This will generate error if you executed myapp.py directly as a script so handle accordingly

  2. update the sys.path by appending lib.py's path (Not Recommended)

    sys.path.append("....../lib.py")

watch this for clear understanding.

Also just to point out, __name__=="__main__" is only true when you execute the file directly. so the code inside if in myapp.py will not work when you'll use it as a module in package.

I hope this was helpful :)