简体   繁体   中英

How to solve: attempted relative import with no known parent package

I have a project structure with mostly empty python files:

-project
  --work1
      --__init__.py
      --app.py
      --momo.py

momo.py

import numpy as np
def plus(x):
    return x

app.py

from . import momo
a = momo.plus(6)

Running app.py directly results in this error:

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

I have tried change to "from plus import momo" but this yields the same error.

Python version 3.8

Any hints would be much appreciated.

You shouldn't import like you said.

you can just try this:

import momo

it should add momo to your current file.

and for using functions which has been declared in momo , you should call the function name after momo. . for example:

a = momo.plus(12)

if you just want to import plus`` from momo``` file, you can try

from momo import plus

then you just need to call function name, instead of the whole file and functions together. eg:

a = plus(12)

Try running it from project directory as module (-m flag):

$ cd project
$ python -m work1.app 

because when you're starting app directly like python app.py , is doesn't know that current folder is actually a package with __init__.py but dot in from. import * from. import * is a shortcut for a current package.

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