Point to import a specific function from a module in Python

Well, the name is a little explanatory. If I import the following:

 import urllib.request

Other functions from urllib will also be available in the script as urllib.parse, urllib.error. So how is this different from importing everything:

import urllib

The examples may seem simple, but sometimes I have a larger tree with several nested modules and packages, and if I want:

import level1.level2.level3.level4

Should I just import level1 and import the whole tree?

+4
source share
1 answer

No difference:

$ python3.2
Python 3.2.5 (default, Mar 10 2014, 10:39:23)
[GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.2.79)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import urllib
>>> import urllib.request as urllib_request
>>> urllib.request is urllib_request
True

Both import urlliband import urllib.requestwill import the module .

: from <module> import <object> .

:

$ python3.2
Python 3.2.5 (default, Mar 10 2014, 10:39:23)
[GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.2.79)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from urllib.request import urlopen
>>> urlopen
<function urlopen at 0x1015f6af0>

, urlopen - . :

>>> import sys
>>> sys.modules["urllib"]
<module 'urllib' from '/usr/local/Cellar/python32/3.2.5/Frameworks/Python.framework/Versions/3.2/lib/python3.2/urllib/__init__.py'>
>>> sys.modules["urllib.request"]
<module 'urllib.request' from '/usr/local/Cellar/python32/3.2.5/Frameworks/Python.framework/Versions/3.2/lib/python3.2/urllib/request.py'>

urllib.request.urlopen, : urllib urllib.request.

: https://docs.python.org/3.4/tutorial/modules.html

+2

Source: https://habr.com/ru/post/1540169/


All Articles