Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

`from ... import` vs `import .` [duplicate]

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)?

like image 363
wchargin Avatar asked Feb 24 '12 23:02

wchargin


People also ask

What is from import * in Python?

In Python, you use the import keyword to make code in one module available in another. Imports in Python are important for structuring your code effectively. Using imports properly will make you more productive, allowing you to reuse code while keeping your projects maintainable.

What happens if I import the same module twice?

The rules are quite simple: the same module is evaluated only once, in other words, the module-level scope is executed just once. If the module, once evaluated, is imported again, it's second evaluation is skipped and the resolved already exports are used.

Why do we use from in Python?

import Python: Using the from Statement If this is the case, you can use the from statement. This lets you import only the exact functions you are going to be using in your code. We use the from keyword, followed by random, to tell our program that we want to import a specific function from the “random” module.

What are the three types of import statement in Python?

There are generally three groups: standard library imports (Python's built-in modules) related third party imports (modules that are installed and do not belong to the current application) local application imports (modules that belong to the current application)


1 Answers

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

from urllib import request # access request directly. mine = request()  import urllib.request # used as urllib.request mine = urllib.request() 

You can also alias things yourself when you import for simplicity or to avoid masking built ins:

from os import open as open_ # lets you use os.open without destroying the  # built in open() which returns file handles. 
like image 196
g.d.d.c Avatar answered Oct 02 '22 20:10

g.d.d.c