简体   繁体   中英

ImportError: attempted relative import with no known parent package - Python

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

I've had similar issues and I've created an experimental new import library ultraimport that allows to do file system based imports to solve your issue.

In your test.py you could then write:

import ultraimport
Scheduler = ultraimport('__dir__/testclass.py', 'Scheduler')

This will always work, no matter what is your folder structure, no matter if you run the code as a script or module and it does not care about sys.path or your current working directory. It's also not necessary to create __init__.py files.

One caveat when importing scripts like this is if they contain further relative imports. ultraimport has a builtin preprocessor to rewrite subsequent relative imports to ultraimports so they continue to work. Though, this is currently somewhat limited as original Python imports are ambiguous and there's only so much you can do about it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM