0

I am new in python and trying to understand the difference between "import module" and "from module import *". I was thinking both are the same as they import all the functions from the module but doesn't see so. My confusion stems from the below code--

import abc
class Minnn(ABC):
    @abstractmethod
    def calculate(self, x):
        pass  # empty body, no c

When I run, I get the following error saying "NameError: name 'ABC' is not defined". When I replace the first import line with "from abc import *" then it works. So why is this causing a difference

user496934
  • 3,822
  • 10
  • 45
  • 64
  • 2
    related: https://stackoverflow.com/questions/710551/use-import-module-or-from-module-import, besides it depends on where `ABC` is defined inside the `abc` module – EdChum May 03 '19 at 11:14
  • 2
    Possible duplicate of [Use 'import module' or 'from module import'?](https://stackoverflow.com/questions/710551/use-import-module-or-from-module-import) – nickyfot May 03 '19 at 11:16
  • Duplicate of https://stackoverflow.com/questions/12270954/difference-between-import-x-and-from-x-import – RajmondX May 03 '19 at 11:18
  • Related: https://stackoverflow.com/questions/55722260/what-is-the-reason-for-using-a-wildcard-import – CristiFati May 03 '19 at 11:24

1 Answers1

2

Importing a module adds a single symbol into the namespace, but from which you can reference exported objects:

# simple import
import abc

abc.ABC
abc.ABCMeta

# renamed via "as"
import abc as module
module.ABC
module.ABCMeta

When you import *, you are adding all exported symbols from that module into the current namespace, and so you can reference them directly without the module prefix:

#### YOU PROBABLY SHOULD NOT DO THIS
from abc import *
####

ABC
ABCMeta

If you're hacking in a shell or notebook; not a big deal. But production code should not do this.

Nino Walker
  • 2,742
  • 22
  • 30
  • 1
    Since @user496934 is new to the language, maybe you should include that import * is bad form. – Nathan May 03 '19 at 11:21