-1

Probably a simple question, but I'm just getting started with Python and try to understand how the library stuff works.

So my question is why do I need to type

from tqdm import tqdm

instead of just

import tqdm

like with other libraries?

I get that when you only need one part of a library you can do this. But in this case my program doesn't work if I don't do it. Shouldn't be everything included with the second expression? If I run my program with it I get the error:

"TypeError: 'module' object is not callable"

Ateblade
  • 3
  • 1
  • It's so you just have to type `tqdm()` and not `tqdm.tqdm()` every time. – Random Davis Dec 09 '20 at 21:36
  • You *don't have to*. When you do `from some_module import some_name` then you import the whole module, and assign `some_name` to `some_name` in that scope. If you use `import tqdm` you could use `tqdm.tqdm`, it just happens to use the same name as the module. Indeed, `import tqdm` would generally be preffered – juanpa.arrivillaga Dec 09 '20 at 22:26
  • 1
    Now, `some_name` may itself be another module, but it doesn't have to be. And in the case of `tqdm.tqdm` it is not. Here is the relevant [documentation](https://docs.python.org/3/reference/simple_stmts.html#import) btw – juanpa.arrivillaga Dec 09 '20 at 22:32

3 Answers3

0

from tqdm import tqdm means you're importing module tqdm under tqdm.

import tqdm means importing whole package. In this case you've to use tqdm.tqdm() which is equivalent to using just tqdm() in the above case.

Harish Vutukuri
  • 1,097
  • 4
  • 13
0

The first tqdm is the name of the package or module. The second tqdm is a callable defined under that package/module. It could have been a different callable, such as trange:

from tqdm import trange

What you are basically doing is importing the tqdm callable inside the tqdm module.

bkakilli
  • 358
  • 2
  • 9
0

The package tqdm has a module named tqdm inside it. Now to your tqdm you can

  1. Import all the modules in package tqdm and use the module called tqdm by:
import tqdm

for i in tqdm.tqdm(range(10)):
  pass

OR

  1. Just import the tqdm module of the tqdm package by:
from tqdm import tqdm
for i in tqdm(range(10)):
  pass
mujjiga
  • 12,887
  • 2
  • 22
  • 39