Skip to main content
Stack Overflow
  1. About
  2. For Teams

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

Required fields*

python import module from a package

folder structure:

<current dir>
 main.py
 packages <dir>
 __init__.py
 mod.py

main py:

import packages
print packages.mod.hello()

mod.py:

def hello():
 return 'hello'

__init__.py:

from packages import mod

If I run main.py, I get no error. But if I edit __init__.py to 'from packages import *' , I get this error: AttributeError: 'module' object has no attribute 'mod'

I'm not asking how to make that 'print' command work. I can use other 'import' syntax in main.py to make it work. The question is: I'm curious about that 'from packages import mod' in the __init__.py. If i can do import mod then when I replace to import *, which means import everything, why do I get an error instead?

So what does the from packages import * really mean inside that __init__.py?

Anyone can help? Thanks

Answer*

Draft saved
Draft discarded
Cancel
3
  • i can do from package import * since there will be no error when compiled, only if i print then it said no module 'mod'. So that command is valid , only i'm confused about what the code is doing . Commented Apr 9, 2016 at 10:13
  • "You can only import modules, not packages," suggests that packages and modules are mutually exclusive. However, per The Python Language Reference, §5.2 Packages: "[A]ll packages are modules, but not all modules are packages. ... [P]ackages are just a special kind of module." Further a package can be imported: "When a regular package is imported, this __init__.py file is implicitly executed, and the objects it defines are bound to names in the package’s namespace." Commented May 6, 2022 at 16:23
  • See When you "import" a package you actually import the module __init__.py. in answer. This is essentially what you say. Not? Commented May 19, 2022 at 7:30

lang-py

AltStyle によって変換されたページ (->オリジナル) /