如何导入自定义Python包并访问markets包内模块?
markets Module Import Issue Let's work through this step by step to get you accessing the Player class properly. The key issue here is that importing the top-level markets package doesn't automatically pull in all its internal modules/classes unless you explicitly set that up. Here's what to check and fix:
1. First, Confirm Your Directory Structure
Make sure your markets package is organized correctly under ~/python_lib. It should look something like this (adjust based on where Player is actually defined):
~/python_lib/ └── markets/ ├── __init__.py └── [your_module_name].py # e.g., players.py, where the Player class lives
If Player is nested deeper (like markets/core/players.py), note that path too—we'll need it for imports.
2. Check Your __init__.py Content
If your __init__.py is empty (or doesn't include imports for Player), importing markets only loads the package itself, not the internal classes. You have two options here:
Option A: Update __init__.py to Expose Player
Add a line to markets/__init__.py that imports Player from its module. For example, if Player is in players.py:
# markets/__init__.py from .players import Player
Now, when you run import markets in IPython, you can create a Player instance with:
p = markets.Player()
Option B: Import Directly from the Submodule
If you don't want to modify __init__.py, just import Player directly from its module. Using the same players.py example:
from markets.players import Player # Now this works: p = Player()
Or if you prefer to keep the module namespace:
import markets.players p = markets.players.Player()
3. Verify the Import Worked
After importing markets, run dir(markets) in IPython. You should see Player (if you used Option A) or the name of your submodule (like players) listed. If not, double-check:
- That
~/python_libis indeed insys.path(you said you verified this, but a quickprint(sys.path)won't hurt) - That there are no other
marketspackages/modules in yoursys.paththat might be overriding yours - That the module containing
Playerhas no syntax errors (try runningpython ~/python_lib/markets/players.pyto check for errors)
4. Common Pitfall to Avoid
Don't confuse importing the package with importing its contents. A bare import markets only gives you access to what's explicitly defined in __init__.py—it won't magically load all submodules. That's why you weren't getting an error on import markets, but couldn't access Player directly.
内容的提问来源于stack exchange,提问作者James A. Foster

