Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How did Python called un-imported module?

I used:

import urllib.request 

And then:

d={'value':12345}
urllib.parse.urlencode(d)

I expected python to throw an exception because I didn't imported urllib.parse but instead it worked. What is the reason for it?

P.S: I am using Python 3.3.3

like image 995
svetaketu Avatar asked Oct 21 '22 02:10

svetaketu


1 Answers

Here is the relevant structure for the urllib package in Python 3.3.3

urllib/
    __init__.py   <-- empty file
    request.py
    parse.py

There's a line near the top of the request module which looks like:

from urllib.parse import some, helper, functions

And it's this line that is the cause of urllib.parse being brought into scope.

You can check that executing import urllib.parse, on the other hand, does not trigger an import of urllib.request. It will necessarily bind the urllib name (because urllib.parse itself is not a valid identifier) but it won't import any other submodules.


Note: had you done either of the following

import urllib.request as urllib_dot_request
from urllib import request

Then you would have neither urllib nor urllib.parse available in the namespace. They would still get imported by the module loader, but wouldn't be brought into scope.

like image 96
wim Avatar answered Oct 22 '22 16:10

wim