You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Jupyter无法直接导入包内模块,需使用from...import...的问题咨询

Why doesn't 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 the blah/__init__.py file. Any names defined in that file (variables, functions, imported modules) get added to the blah namespace.
  • If your __init__.py is empty (which it sounds like is the case here), blah won't automatically include submodules like file1 or file2—those only get loaded into the blah namespace 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 file1 in the same command line session. Python caches imported modules, so when you later run import blah, the already-loaded file1 is still present in the blah namespace.
  • 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/file2 that 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 blah then dir(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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 04:04:52