ImportError: attempted relative import with no known parent package when trying to import sibling inside package

Viewed 506

I am trying to build a python package from one of my projects. I have a directory structure like this:

mypackage
    setup.py
    src
        __init__.py
        mypackage.py
        Node.py
        (... and a lot of other files and subdirectories)

In mypackage.py, I import the Node class like this:

from .Node import Node

along with a few other classes, to make them directly accessible when importing mypackage later. However, after successfully building the package (just using pip install "mypackage/" from the mypackage folder's parent dir rn), when trying to import the package in python, I get the following error

    from .Node import Node
    ImportError: attempted relative import with no known parent package

From what I know, mypackage.py should absolutely be part of the package, so I don't really understand why it can't import siblings like this. In the setup.py file, I specify

from setuptools import setup
setup(
    <...>
    py_modules=['mymodule'],
    package_dir={'': 'src'}
)

What am I missing here? I really don't know much about the import and module system in Python.

1 Answers

To do your import you need to just write

import Node

This is because when you write

from .Node import Node

It thinks that your looking for a directory called Node inside the current directory and then import the Node file from there.

Related