[Help]How to use relative import in actions.py

In my actions.py, I use relative import to import other module. When I try to start the action server with the command ‘rasa run actions’, it results in error: ImportError: attempted relative import with no known parent package

Please tell me how should I start action server with relative import?

Hi @yhdrytjd,

can you please post your directory/project structure with everything you want to import and could you please post a few infos about your Rasa version etc. ?

Regards Julian

Hi, the root directory contains the actions.py, domain.yml, etc.

root/
      lib/
          constants.py

In the actions.py, I use relative import: from .lib import constants

it results in error: ImportError: attempted relative import with no known parent package.

I am using rasa 1.6.0

Hi @yhdrytjd,

did you specify lib/ as a package-folder by putting an __init__.py file into it? If so, you can remove the . from .lib to import.

Regards Julian

I tried remove the __init__.py from lib/, but relative import with .lib still does not work with the command ‘rasa run actions’.

I want to test my scripts in lib/ without running rasa actions. The starting folder is in lib/ rather than root/. I need to use relative import to reference the scripts.

Hi @yhdrytjd,

okay, I am going to rebuild your setup and provide some feedback but I need a bit of time for that since I am involved in something else currently.

Stay tuned! :slight_smile: Regards
Julian

were u guys able to figure out something? I am stuck on the same thing

This error occurs when you try to import a module using a relative import, but Python cannot find the module’s parent package.

To fix this error attempted relative import with no known parent package, you need to make sure that the module being imported is part of a package, and that the package is on the Python path. You can do this by adding an empty init.py file to the package’s directory, and by making sure that the directory containing the package is on the Python path.

Alternatively, you can run the module using the -m flag with the Python interpreter, like this:

python -m mypackage.mymodule

This tells Python to run mymodule.py as a module, which will allow it to correctly resolve relative imports.

The main advantage of using relative imports is that they make it easier to move packages and modules around within a project, without having to update all the import statements. They also make it easier to reuse code across multiple projects, because the import paths can be modified to match the package hierarchy of each project.