Accessing python parent folder
Question: I've looked through previous answers which seem to suggest I should be able to
use:

    
    
    from .. import code
    

though it produces this: ValueError: Attempted relative import beyond toplevel
package

though this doesn't seem to be working. My file structure is as follows:

    
    
    scraper/
        __init__.py
        bot/
                scraper.py
                __init__.py
                wigan/ 
                        council.py
                        __init__.py
    

I'm able to from scraper load council using:

    
    
    from wigan import council
    

though from council, none of the following work when trying to load
scraper.py:

    
    
    from .. import scraper
    from scraper.bot import scraper
    from scraper.bot.scraper import scraper
    

Any help would be great. Thanks :-)


Answer: I suspect the problem you're having is that you're running a script that is
located in package. This is one of the most awkwardly supported features in
Python. When you run a script directly, it puts your current path at the start
of the Python search path. If you're inside of a package though, this will be
wrong.

To properly run `scrapper.py` (if that's your script), you should change to
the top level folder (whatever is above `scrapper/`), then run `python -m
scrapper.bot.scrapper`.

Or, if you add that top level folder to the Python search path, either by
using the `PYTHONPATH` environment variable, or by installing it (or an
appropriate `.pth` file) into the `site-packages` folder, then the current
directory restriction will be relaxed and you can run the script from
anywhere.

There are other issues with running modules as scripts if you're also going to
import them by name from other modules. The script will be imported as
`__main__`, not as its actual name. If you import it by name too, you'll get a
second copy of the script, which may mean it doesn't work as intended (if
there is any global state in the module, it may be inconsistent between the
copies). This is one reason it is often suggested that scripts do as little
work as possible (just import something from another module, and then run it).
You may want to refactor your code to do this too.

