Software⏱️ 3 min read📅 2026-06-03

How to Fix: How to fix "Attempted relative import in non-package" even with __init__.py

Learn how to fix: How to fix "Attempted relative import in non-package" even with __init__.py.

Quick Answer: Try checking your system settings or restarting.

The 'Attempted relative import in non-package' error occurs when you try to perform a relative import within a file that is not part of a package. In your case, the issue arises from trying to import from `components.core` in `core_test.py`, which is outside of the `pkg` package.

This error affects developers who attempt to follow PEP 328 without properly structuring their project directory.

🔍 Why This Happens

  • The primary cause of this issue is that `core_test.py` does not have a direct parent package. To resolve this, you need to ensure that the file containing the import statement is part of an explicitly declared package.
  • If you are using Python 3.3 or later, you can use the `__init__.py` file in your package directory to make it a package.

🔧 Proven Troubleshooting Steps

Creating a separate package for components

  1. Step 1: Create a new directory named `components` within the `pkg` directory.
  2. Step 2: Move the `core.py` file into this new directory, making sure it has an `__init__.py` file as well to make it a package.
  3. Step 3: Update your import statement in `core_test.py` to use the relative path correctly: `from .components.core import GameLoopEvents`. The dot (`.`) represents the current package.

Using absolute imports

  1. Step 1: Alternatively, you can perform an absolute import by using the full path to the module: `from pkg.components.core import GameLoopEvents`.
  2. Step 2: This method is more explicit and avoids potential issues with relative imports in non-package files.

✨ Wrapping Up

By following these steps, you should be able to resolve the 'Attempted relative import in non-package' error. Remember to structure your project correctly and use either absolute or relative imports depending on your specific needs.

Did this fix your problem?

If not, try searching for specific error codes.

🔍 Search Error Database

❓ Frequently Asked Questions