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)?
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.
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.
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.
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)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With