How do Python (3.3) packages work?

I am using Python 3.3, testing this on Windows. I do not understand anything. Why when I do this:

>>> import urllib

I get an error

>>> urllib.request
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'request'

and

>>> dir(urllib)
['__builtins__', '__cached__', '__doc__', '__file__', '__initializing__', 
 '__loader__', '__name__', '__package__', '__path__']

There is no request, so it looks durable. However, when importing a submodule request:

>>> import urllib.request

It seems to work

>>> urllib.request
<module 'urllib.request' from 'C:\\Python33\\lib\\urllib\\request.py'>

And now it automatically dir(urllib)shows:

>>> dir(urllib)
['__builtins__', '__cached__', '__doc__', '__file__', '__initializing__', 
 '__loader__', '__name__', '__package__', '__path__', 'error', 'parse', 
 'request', 'response']

Why can't I see after import urlliball the submodules? According http://docs.python.org/3.3/library/urllib.html#urllib.urlopen it should be request, error, parse, parserobots. Is it different from other OS?

+3
source share
3 answers

When you

>>> import package
>>> package.something

, , something, package/__init__.py. , - , . .

Python web.py, (github).

>>> import web  # which is a package
>>> web.httpserver  # which is a module located in web/httpserver.py
<module 'web.httpserver' ...>

, web/__init__.py import httpserver .

Python 3. Python 3, , Python 2. urllib/__init__.py import , request, . Python 3 import "" __init__.py. , .

: import urllib.request dir(urllib) , response. , , urllib.request, import. import urllib.error, request, error . , Python - (, "" sys.modules).

+2

urllib - . , ; urllib.request.

0

dir(). , , , - __init__.py. request urllib __init__, .

, " " - - - . __init__.py, ( , __init__). , (, urllib), ( "" " " ) , "" ( __init__.py __init__ , - , ?).

- __init__, , ( ). , . . :

  • __init__.py , __init__

  • subodule for the package, which method (function attribute) is intended for the object

  • subpackage for the package which field (non-functional attribute) for the object.

Why? __init__takes care of the installation of objects, submodules / methods are ways of storing logic in one place, and subpackages / fields are ways of organizing other submodules / methods or sub-subpackages / fields.

To be honest: this does not work in CPython, but it is a pretty good model for understanding how it will behave.

0
source

All Articles