user59419
user59419

Reputation: 993

Importing a module to another module in Python

Assume I have the following package structure:

A/
  __init__.py
  B.py
  C.py
Test.py

Now I am wondering what would be the difference between the following two lines of code:

from A.B import *
import A.B

I know the first line will import everything from the B.py but then what is the point of the second line if it does not import the content of the B.py?

If it is bad to write from A.B import *

EDIT: then how about using

from A import *

This will run everything in the init.py file. Can anyone explain what is wrong with the statement and why it should not be used? I thought importing a package is like running it so if I write

import A

Then I automatically run the init.py, is this correct?

Upvotes: 2

Views: 81

Answers (2)

Samwise
Samwise

Reputation: 71464

The difference is in the name binding. from A.B import * will import everything in B into the current module as a top-level name. import A.B will import the A.B module as A.B.

The second one is generally considered superior because anything you use from A.B later in the file will be prefixed with A.B, making it obvious where it was imported from. With an import * statement you can't tell at a glance what you're importing or what name it will be imported under.

Upvotes: 1

FLAK-ZOSO
FLAK-ZOSO

Reputation: 4102

There's no difference, but notice that:

from module import *
functionComingFromModule()
import module
module.functionComingFromModule()

That's the difference.

Upvotes: 1

Related Questions