Question about Lesson 22's use of "import"

0 Benjamin Grant · March 28, 2015
In Lesson 22 (or the new group) Bucky uses the following line of code:

"import urllib.request"

I've tried to look up Python syntax with the import command, but I am not finding what I am seeking:

Why can't Bucky just do "import urllib"? When one uses syntax like "import first.second" what is the meaning of "first" and what is "second"? What does the dot indicate in an import statement like that?

Thanks. I'm a noob. ;)

Post a Reply

Replies

Oldest  Newest  Rating
+1 alex constantin · March 28, 2015
The first which you describe is the main library or module and the second is a class inside the main module.

These two lines do exactly the same:

import urllib.request

from urllib import request


The advantage of writing the second line instead of the first is that when you want to use it later in your code, you can just write 
request


instead of
urllib.request

However, you can also use the as keyword in the first line to reference it to any word you want:

import urllib.request as req
0 Benjamin Grant · March 28, 2015
Hmmm... but if that were the case, I should be able to find a "urllib.py" module with a "request" class defined inside it, yes? And I'm checking the path via PyCharm and I cannot find any urllib.py module at all?

And in Bucky's example, it doesn't seem like the "request" he is referencing is a class, but a function - although I may well be wrong about this, being so new.

So still a bit confused.
0 Chris Weaver · March 30, 2015
you can always use help(urlllib) or whatever module
or just look at the pydocs

Classes offer you specific Methods && ways of dealing with specific Objects that's about it!!
you never have to declare a Class in your scripts
you just use the Methods

import urllib
req = urllib.urlopen('http://thenewboston.com')     GET [Method] this is an HTTP:// 'request'
data = req.read()
print data


It helps to use a Proxy between your Browser && the web so as you can see what happens behind the scenes..
This will help you understand GET, POST, PUT etc.. .  Methods
  • 1

Python

107,237 followers
About

This section is all about snakes! Just kidding.

Links
Moderators
Bucky Roberts Administrator