简体   繁体   中英

Cannot import name 'function' from 'module.py' - same directory, another function from the same module imports

I have a Jupyter Notebook - we'll call it main , and I'm running it piecemeal in Jupyter Lab 3.0.14 using a Python 3 environment.

Within this notebook, I'm trying to import custom functions from a module, we'll call this one module.py , which is in the same directory as main .

It looks something like this:

// main

import sys
import os
from module import foo, bar

// module.py

def foo():
    return

def bar():
    return

When I run the import statements in main , it throws an error

ImportError: cannot import name 'bar' from 'module' (/module.py)

If I run

from module import foo

or

from module import *

It's fine (although calling the functions will throw an error that the function is not defined ). In fact, it will import foo even if there's no function named foo in module.py . It won't import any of my own functions by name. I feel like I must be missing something fundamental, here...

Any help would be greatly appreciated!!

Okay, this is my first time using Jupyter Lab, and this problem came from a fundamental misunderstanding of how Jupyter (and maybe other IDEs?) manages packages.

In short, as I understand it, re-running the code which imported functions from module.py did not actually re-import the contents. The only things it imported were what I asked for the first time, and any subsequent calls to import functions only referenced that first static image I pulled.

Therefore, if module.py had one function, foo , and I ran:

from module import foo

...then made some changes, such as editing the contents of foo and adding bar , running:

from module import foo, bar

...didn't actually do anything but reference that first copy of module.py I pulled. Because bar didn't exist the first time I ran the import function, it "couldn't see it", no matter how many times I re-ran the import function. I had to restart the kernel to fix it, basically.

I noticed this because when I changed the name of the script, it would import the functions that weren't previously working, but then edits to the functions, even once imported, weren't recognized.

This link provided the clue I needed to figure this out.

Hopefully this helps somebody!

Restart the kernel in the Jupiter notebook. I solved a similar import name issue by restarting the kernel.

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