-1

I'm currently trying to learn python as my first language. I'm wondering what's the difference between:

Import OtherModule

and:

From OtherModule Import *

Doesn't both of these rows include everything that's inside of OtherModule?

I've tried doing both but can't see any difference?

2 Answers2

0

Consider the following code:

% python
>>> import math
>>> math.sqrt(100)
10.0
>>> from math import sqrt
>>> sqrt(100)
10.0

The math module is the home of the sqrt function.

After we import the math module, we have access to all of the functions in the math module.

When we import the sqrt function, we can access the sqrt function by its name, without having to reference the parent module.

That summarizes the difference between two types of import statements:

import <module>    
from <module> import <function_variable_or_class>

The syntax from <module> import * imports all functions, variables, and classes from a module, so that we can access them by name without referencing the parent module.

For example,

% python
>>> from math import *
>>> sqrt(100)
10.0
>>> pi
3.141592653589793
ktm5124
  • 11,861
  • 21
  • 74
  • 119
0

It's not true that from OtherModule import * gives you access to everything that's inside OtherModule. For example it does not import variables whose name starts with _. And each module can have a different definition on how the wildcard * should behave.

In practice (most cases), both statements will give you access to everything you care about and the main difference is in the namespace to which names are bound: whether you will reference to the function foo from OtherModule as OtherModule.foo() or just foo(). See the examples from the docs.

However, it's considered a bad practice to use from OtherModule import *.

Although certain modules are designed to export only names that follow certain patterns when you use import *, it is still considered bad practice in production code.

Remember, there is nothing wrong with using from package import specific_submodule! In fact, this is the recommended notation unless the importing module needs to use submodules with the same name from different packages.

Among other reasons, this is because:

  • in most cases, you don't know/remember what you are importing (I don't think anybody knows every function name in numpy) and there's a chance you may overshadow a name by accident.

  • references to names from that module are not explicit anymore.

Of course, as with many "bad practices", there are exeptions. But, as with most exeptions from bad practices, don't use them unless you are really sure on what you're doing.

Ignatius Reilly
  • 1,594
  • 2
  • 6
  • 15