Importing modules from different directories
Question: What is the pythonic way for absolute importing modules located in different
directories in Python 3? I am able to import modules by modifying the
`sys.path` but that method is hackey.

The alternative method, from what I've read, is to turn the project into a pip
installable package. This is method beyond me, can someone elaborate on this
process and logic? After writing a `setup.py` script, do I just `python
setup.py install`, then all my modules and packages are in the right path and
will work?


Answer: ## Loading a script dynamically from anywhere via a given path

    
    
    import importlib.machinery
    import imp
    import os.path
    
    path = '/home/user/testscript' # without .py
    fname = os.path.basename(path)
    
    namespace = fname.replace(' ', '_').strip('\\/;,. ') 
    
    loader = importlib.machinery.SourceFileLoader(namespace, os.path.abspath(path+'.py'))
    handle = loader.load_module(namespace)
    imp.reload(handle)
    
    ret = handle.mainFunction()
    

`handle` being your library name. I just call it handle because I use it in a
one shot test library myself so it gets deleted anyway in every iteration of
the loop.

Sorry for syntax issues, wrote it on the phone. I'll correct any syntax issues
or indentation issues in a few min.

## Minimalistic example would be:

    
    
    import importlib.machinery
    
    # Register the "mylib" namespace as "test.py"
    loader = importlib.machinery.SourceFileLoader("mylib", r'C:\Users\OpenWindows\Desktop\test.py')
    # And load that namespace
    mylib = loader.load_module("mylib")
    
    # And now we can call it whenever we want.
    ret = mylib.someFunction()
    

## Traditional approach (not absolute path friendly)

Would be to just create a folder structure that looks like this:

    
    
    |- main.py
    |-- mylib /
    |--        __init__.py
    |--        mylib.py
    

And in the `__init__.py` file create something that looks like:

    
    
    from mylib.mylib import *
    

That way, any function or class in `mylib.py` would be imported as if it
resided in `main.py`. However, again this is heavily dependant on the
subfolder residing in the same folder as the script you're executing. But it's
also a traditional way of shipping/adding functionality to a application.

There's some other stuff you can do in the
[`__init__.py`](https://docs.python.org/3/tutorial/modules.html#packages) file
that might be useful. Have a look at the documentation.

