Back

Explore Courses Blog Tutorials Interview Questions
0 votes
3 views
in Python by (20.3k points)

I'm wondering if there's any difference between the code fragment

from urllib import request

and the fragment

import urllib.request

or if they are interchangeable. If they are interchangeable, which is the "standard"/"preferred" syntax (if there is one)?

Thanks!

2 Answers

0 votes
by (40.4k points)

The difference between import module and from module import foo is mainly subjective. Pick the one you like best and be consistent in your use of it. Here are some points to help you decide.

import module

Pros:

Less maintenance of your import statements. Don't need to add any additional imports to start using another item from the module

Cons:

Typing module.foo in your code can be tedious and redundant (tedium can be minimized by using import module as mo then typing mo.foo)

from module import foo

Pros:

Less typing to use foo

More control over which items of a module can be accessed

Cons:

To use a new item from the module you have to update your import statement

You lose context about foo. For example, it's less clear what ceil() does compare to math.ceil()

Either method is acceptable, but don't use from module import *.

For any reasonably large set of code, if you import * you will likely be cementing it into the module, unable to be removed. This is because it is difficult to determine what items used in the code are coming from 'module', making it easy to get to the point where you think you don't use the import any more but it's extremely difficult to be sure.

0 votes
by (106k points)

It depends on how you want to access the import when you refer to it.

from urllib import request 

mine = request() 

import urllib.request 

mine = urllib.request()

Related questions

+3 votes
2 answers
0 votes
1 answer
0 votes
2 answers
asked Oct 3, 2019 in Python by Tech4ever (20.3k points)
Welcome to Intellipaat Community. Get your technical queries answered by top developers!

28.4k questions

29.7k answers

500 comments

94k users

Browse Categories

...