from typing import Optional
import asyncio


def get_non_running_loop() -> Optional[asyncio.AbstractEventLoop]:
    """If there is an existing runloop on this thread and it isn't running return it.
    If there isn't one create one and return it.
    If there is an existing running loop on this thread then return None.
    """
    try:
        loop = asyncio.get_event_loop()
    except RuntimeError:
        # In Python 3.6 trying to get an event loop when none can be automatically created is a an exception
        return asyncio.new_event_loop()
    else:
        if loop.is_running():
            # There is already a running loop on this thread so we will need to spawn a new thread if we want to run one
            return None
        else:
            # We have An existing event loop, but it is not running, so we can run it.
            return loop