Jupyter无法直接导入包内模块,需使用from...import...的问题咨询
import blah automatically load file1 in Jupyter Notebook? Let's break down what's happening here, and why you're seeing different behavior between Jupyter and the command line.
The Core Python Import Mechanism
First, let's clarify how Python handles package imports:
- When you run
import blah, Python only executes theblah/__init__.pyfile. Any names defined in that file (variables, functions, imported modules) get added to theblahnamespace. - If your
__init__.pyis empty (which it sounds like is the case here),blahwon't automatically include submodules likefile1orfile2—those only get loaded into theblahnamespace when you explicitly import them (e.g.,from blah import file1).
That's exactly why you see file1 appear in dir(blah) only after you run from blah import file1 in your notebook.
Why Does the Command Line Seem to Work?
The "normal" behavior you see in the command line is almost certainly due to one of these scenarios:
- Module caching: You might have previously run
from blah import file1in the same command line session. Python caches imported modules, so when you later runimport blah, the already-loadedfile1is still present in theblahnamespace. - Hidden explicit imports: If you're running a script in the command line instead of typing commands interactively, that script might include explicit imports of
file1/file2that you're not accounting for. - Misremembered steps: It's easy to mix up the order of commands—try restarting your command line Python interpreter from scratch, run only
import blahthendir(blah), and you'll likely see the same result as your notebook.
How to Make import blah Load file1 Automatically
If you want file1 (and file2) to be available immediately when you import blah, just add explicit import statements to your blah/__init__.py:
# blah/__init__.py from . import file1 from . import file2
Now, whenever you run import blah, Python will execute these lines, load the submodules, and they'll show up in dir(blah) right away.
内容的提问来源于stack exchange,提问作者codythecoder

