srini
srini

Reputation: 201

Python: Importing modules and libraries

Whats the difference between the following statements:

  1. import os

  2. from os import *

Do they mean one and the same thing? If so, why two ways of saying it?

Upvotes: 1

Views: 142

Answers (2)

Mihai.Mehe
Mihai.Mehe

Reputation: 504

import os

brings the name os into the namespace and thus the os name becomes unique.

so using os.read(fd, n) will read n bytes from the file descriptor fd.

from os import *

brings all the names from the module os into the global namespace. Thus we can use read(fd,n) directly.

Problem with from os import * :

If we have our own function read(fd,n) in the local namespace, by using from os import * we get 2 functions with the same name, and the interpreter uses the local function with that name.

If we create a module with a read(fd,n) function having the same name as the one in os module (both function names will be in the global namespace), the interpreter will only use one of them.

Upvotes: 1

BlueSheepToken
BlueSheepToken

Reputation: 6169

from os import * imports all methods from os, and should be avoided.

import os just import the namespace and allows you to call methods from os by prefixing with os.

Upvotes: 1

Related Questions