How to import from a sibling directory in python3?

You could remove the dots, and it should work:

# parsemessages.py
from helpers import parse
parse.execute("string to be parsed")

That's probably your best solution if you really don't want to make it a package. You could also nest the entire project one directory deeper, and call it like python3 foo/bot.py.

Explanation:

When you're not working with an actual installed package and just importing stuff relative to your current working directory, everything in that directory is considered a top-level package. In your case, bot, plugins, helpers, and commands are all top-level packages/modules. Your current working directory itself is not a package.

So when you do ...

from ..helpers import parse

... helpers is considered a top-level package, because it's in your current working directory, and you're trying to import from one level higher than that (from your current working directory itself, which is not a package).

When you do ...

from .helpers import parse

... you're importing relative to plugins. So .helpers resolves to plugins.helpers.

When you do ...

from helpers import parse

... it finds helpers as a top-level package because it's in your current working directory.


If you want to execute your code from the root, my best answer to this is adding to the Path your root folder with os.getcwd(). Be sure your sibling folder has a init.py file.

import os
os.sys.path.insert(0, os.getcwd())

from sibling import module