urllib has many different types of openers. Well, ok, it has a couple, not many, but that's beside the point. If you call urllib.open
the way you want, how is urllib supposed to know which opener you intend to use?
It knows this because your "intermediate step" created an instance of a particular type of opener. If you create an instance of FancyURLOpener
, python will know that that is the particular type of opener that you want. If you want to use URLOpener
instead, create an instance of that, and then you can use it instead.
Don't think of this as an intermediate step, think of it as the step -- the way to tell python "this is the specific type of url opener I want to use".
Now, of course, python could have been written in a non-OO way and had you tell the open method what type of opener you wanted to use. For example, a non-OO way might have you do this: f = urllib.open({}, type="Fancy")
. That could work, right? Many people write code in that style and it works, so why bother with objects?
Using an object oriented method means you can create your own opener with its own special properties. For example, the documentation for the fancy version says it "[provides] default handling for the following HTTP response codes: 301, 302, 303, 307 and 401". What if you also want default handling of 404? You might call this the CJOpener, but in order to use it you would have to modify urllib
itself to take "CJ" as well as "Fancy" as that last parameter. Do you really want to be modifying the built-in python code?
Classes and objects are the solution. The class defines the interface -- the standard way that an opener should work. You are free to create your own variations, and all you have to do is create a subclass, and then create an instance of that subclass. Once you do that, any python code anywhere in the world that knows how to work with FancyURLOpener
and URLOpener
instantly knows how to work with your opener, too.
So, the advantage of this intermediate step is a convenient way to tell python which variation of a common API you want to use. All programs that know how to use this API will also know how to use your version of the API too (assuming you don't break the standard API).