简体   繁体   中英

Why does this import give me an error message when trying to import from 2 local modules?

I have the following code structure:

Graph API/
│── main.py
├── helper_functions/
    ├── defines.py
    ├── insights.py

insights.py imports 2 functions from defines.py at the beginning:

from defines import getCreds, makeApiCall

It then uses "makeApiCall" for this function:

def getUserMedia( params ) :
    // Some code about url endpoints etc. 

    return makeApiCall( url, endpointParams, params['debug'] ) # make the api call

I want to use the getUserMedia function in the main.py script, so I import it with:

from helper_functions.insights import *

But I get the error:

Traceback (most recent call last):
  File "/Users/Graph_API/main.py", line 1, in <module>
    import helper_functions.insights
  File "/Users/Graph_API/helper_functions/insights.py", line 1, in <module>
    from defines import getCreds, makeApiCall
ModuleNotFoundError: No module named 'defines'

What leads to this error? When I use the getUserMedia function within insights.py it works fine. I already tried importing defines.py to main.py as well, but I get the same error.

I am pretty new to programming, so I would really appreciate your help :)

You should replace

from defines import getCreds, makeApiCall

With

from helper_functions.defines import getCreds, makeApiCall

Or

from .defines import getCreds, makeApiCall

You must give a path either from project directory as in the first example, or from the relative path from the insights file by adding a dot.

You could also consider adding init .py to the helper_functions folder. Checkout here: What is __init__.py for?

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