0

from module import * VS import module

What I know

I know the difference between the 2, the difference is when you are using from module import *, you can just refer the classes, functions etc. in the module just like they are defined in the file they are imported in itself.

But when you are just usingimport module, you have to use module. before the name of the object to refer it.

The problem

So what I don’t know is why is it sometimes considered bad practice to use from module import * instead of import module?

InfoDaneMent
  • 326
  • 3
  • 18
  • 1
    Only import what you need: [use-import-module-or-from-module-import](https://stackoverflow.com/questions/710551/use-import-module-or-from-module-import) - doing the * import clutters your namespace. In your kitchen, do you prefer a drawer that contains pots, another drawer that contains knifes and forks and spoons and a drawer that contains cling film (urks) etc. or do you want to have a wild assortment of knifes, cling film, pots, forks and spoons flying around. With imports it is even more so: there may be name collisions if you just throw all of them inside your namespace. – Patrick Artner Oct 21 '21 at 14:04

1 Answers1

1

PEP 8 states that

Wildcard imports (from <module> import *) should be avoided, as they make it unclear which names are present in the namespace, confusing both readers and many automated tools. There is one defensible use case for a wildcard import, which is to republish an internal interface as part of a public API (for example, overwriting a pure Python implementation of an interface with the definitions from an optional accelerator module and exactly which definitions will be overwritten isn't known in advance).

Daweo
  • 31,313
  • 3
  • 12
  • 25