0

My folder structure is (using Pycharm),

project
-testclass.py
-__test__.py

i am trying to call the test class method from test.py. But getting below exception

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

test.py:

import asyncio
import sys
from .testclass import Scheduler

async def main():
    print("main")
    scheduler = Scheduler()
    scheduler.run()

if __name__ == "__test__":
    main()
    try:
        sys.exit(asyncio.run(main()))
    except:
        print("application exception")

testclass.py:

class Scheduler:
    def __init__(self):
        print("init")

    async def run(self):
        print("run")

How to resolve the correct import & it says relative import! How do i get this working in pycharm.

Edit: folder structure now changed as below as suggested.

project_folder
 testpack (->python package)
  - __init__.py
  - testclass.py
 -__init__.py
 -__test__.py
Satscreate
  • 495
  • 12
  • 38
  • 1
    The problem has nothing to do with PyCharm, but with Python itself. Since your files are not in a package structure, the relative import won't work. You could import testclass as another module outside a package with just `import testclass`. Or you could create a package structure by creating an appropriately named folder and including an `__init__.py` – Grismar Jul 01 '22 at 07:09
  • Hi @Grismar moved testclass.py under testpack (which is python package). Now program runs but i dont see any print in console. Why? – Satscreate Jul 01 '22 at 07:24
  • Please update your code and question to reflect the current situation - it's impossible to say without knowing what your situation is. – Grismar Jul 01 '22 at 07:44
  • with the folder structure described in the question all you have to do is remove the `.` in `from .tesclass ...` – Alexander Jul 01 '22 at 07:44
  • Please see https://stackoverflow.com/questions/16981921/relative-imports-in-python-3. The short version is that you are not intended to have scripts (i.e., something you run like `python whatever.py`) inside your packages, only modules (i.e. things that you `import`, or run like `python -m what.ever`). Best practice is to keep your entry-point scripts outside of the package hierarchy, and/or use [the packaging system](https://packaging.python.org/en/latest/) to create executable entry-point wrappers. Failing that, design for use with the `-m` option, or be prepared for some hacking. – Karl Knechtel Jul 01 '22 at 08:27

0 Answers0