Python's powerful own modules-standard library

Source: Internet
Author: User

Introduction: Python's power is embodied in "module confidence", because Python not only has a very strong own module (standard library), but also a large number of third-party modules (or packages, libraries), and many developers are constantly contributing to their own development of new modules (or packages, libraries). This article will give you an overview of Python's own module, the standard library.
This article is selected from the old Ziko python: Easy to get started.

"Python comes with ' batteries ', which has been circulating for a long time."
When Python is installed, a number of modules are installed on the local computer as well. These things are like "power," so Python has a lot of life and can easily use many modules for free. Therefore, it is called "own battery".
The modules that are installed by default when you install Python are collectively referred to as the "standard library."
Familiarity with the standard library is something you must do to learn programming.

How to refer

All modules are subject to the following references, the most basic, the most commonly used, or the very good readability of the reference method.

Import ModuleName

For example:

>>> import pprint>>> a = {"lang": "Python",  "book": " Www.itdiffer.com ", " Teacher ":" Qiwsir ", " goal ":" From beginner to master "}>>  pprint.pprint (a) {' book ':  ' www.itdiffer.com ',  ' goal ':  ' from beginner to  Master ',  ' lang ':  ' python ',  ' teacher ':  ' Qiwsir '} 

In the process of explaining the module, take the standard library pprint as an example.
Using one of the methods in the module in Pprint.pprint (), this method allows the dictionary to format the output. See if the results are easier to read than the original?
After import, you can theoretically follow a lot of module names. But in practice, it is recommended that you one name at a time, too much is not easy to read.
This is introduced into the module with the import Pprint style, with the dot number "." (English half-width) in the form of a reference to its method.
About the introduction of the module, the previous introduction of the import statement has been said, here again listed, right when review.

>>> from Pprint import pprint

This means that only the Pprint () is introduced from the Pprint module, and then it can be used directly.

>>> Pprint (a) {' book ': ' www.itdiffer.com ', ' goal ': ' From beginner to master ', ' lang ': ' Python ', ' teacher ': ' Qiwsi R '}

A little more lazy. You can also do this:

>>> from pprint Import *

This introduces everything in the Pprint module so that all the available content in the module can be used directly as above.
Admittedly, if you explicitly use which methods or properties in the module, then use a similar from modulename import name1, name2, Name3 ... It is also a must. It is important to remind the reader again that it is not possible to reduce readability because of the introduction of modules, so that others do not know where the present approach comes from.
Sometimes the introduction of the module or method name is a bit long, you can rename it. Such as:

>>> import Pprint as Pr>>> Pr.pprint (a) {' book ': ' www.itdiffer.com ', ' goal ': ' From beginner to master ', ' Lang ': ' Python ', ' teacher ': ' Qiwsir '}

Of course, you can also do this:

>>> from Pprint import Pprint as Pt>>> pt (a) {"book": ' www.itdiffer.com ', ' goal ': ' from beginner to Maste R ', ' Lang ': ' Python ', ' teacher ': ' Qiwsir '}

But in any case, be sure to let others understand, and after a certain period of time, they can also understand.

Deep Dive

Continue to take Pprint as an example, in-depth study:

>>> Import pprint>>> dir (pprint) [' Prettyprinter ', ' _stringio ', ' __all__ ', ' __builtins__ ', ' __doc__ ' , ' __file__ ', ' __name__ ', ' __package__ ', ' _commajoin ', ' _id ', ' _len ', ' _perfcheck ', ' _recursion ', ' _safe_repr ', ' _sorted ' ', ' _sys ', ' _type ', ' isreadable ', ' isrecursive ', ' pformat ', ' pprint ', ' saferepr ', ' warnings ']

Not unfamiliar with Dir (), you can see the properties and methods of Pprint from the results. Some of them begin with a double-drawn line and a single line, so they are removed first, in order not to affect our vision.

>>> [M for M in Dir (pprint) if not m.startswith ('_')] [' prettyprinter ', ' isreadable ', ' isrecursive ', ' Pformat ', ' Pprint ', ' saferepr ', ' warnings ']

For these, to be able to understand their meaning, you can use Help (), such as:

>>> Help (IsReadable) Traceback (recent): File "<stdin>", line 1, in <module>nameerror: Name ' isreadable ' is not defined

It is wrong to do so. Do you know where it's wrong?

>>> Help (Pprint.isreadable)

The front is introduced into the module with import pprint mode.

Help on function isreadable in module pprint:isreadable (object) determine if Saferepr (object) are readable by eval ().

With help information, you can see a detailed description of the method. You can use this method to view the one-to-one, but not many, for each method should be familiar.
It is important to note that the Pprint. Prettyprinter is a class, followed by a method.
And look back at the results of Dir (pprint):

>>> pprint.__all__[' pprint ', ' pformat ', ' isreadable ', ' isrecursive ', ' saferepr ', ' prettyprinter '

Does this result look familiar? In addition to "warnings", the result is the same as the one previously obtained by the list parsing.
In fact, when we use the From pprint import *, it is to introduce the method inside the __all__.

Help, documentation, and source code

Can you remember the properties and methods of each module? Like the properties and methods in the Pprint module that I just queried earlier, can we recite them now? I believe most people can't remember. So, we need to use Dir () and help ().

>>> print (pprint.__doc__) support to pretty-print lists, tuples, &  dictionaries recursively. very simple, but useful, especially in debugging data  Structures. Classes-------Prettyprinter ()     handle pretty-printing operations onto  a stream using a configured    set of formatting  Parameters. Functions---------Pformat ()     format a python object into a  pretty-printed representation.pprint ()     Pretty-print a Python  Object to a stream [default is sys.stdout].saferepr ()      generate a  ' Standard '  repr ()-like value, but protect against recursive     data structures.

PPRINT.__DOC__ is a document that looks at the entire class, and does it know where the entire document is written?
Or use the pm.py file to add the following:

#!/usr/bin/env python# coding=utf-8 "" "#增加的This is a document of the Python module. #增加的 "" "#增加的def Lang (): ... #省略了, the back is omitted.

In the beginning of this file, before all classes, methods, and imports, write a string wrapped in three quotation marks, which is the document.

>>> Import sys>>> sys.path.append ("~/documents/vbs/starterlearningpython/2code") >>> Import pm>>> Print (pm.__doc__) This is a document of the Python module.

This is the way to compose a module document, which is to write the appropriate content at the very beginning of the. py file. This requirement should become a developer's habit.
For Python's standard libraries and third-party modules, not only can you see Help information and documentation, but you can also view the source code as it is open.
Or go back to Dir (Pprint) and have a __file__ property that tells us the location of the module:

>>> print (pprint.__file__)/usr/lib/python3.4/pprint.py

Next, you can see the source code for this file:

$ more /usr/lib/python3.4/pprint.py#  author:      fred  l. drake, jr ... "" support to pretty-print lists, tuples, &  Dictionaries recursively. very simple, but useful, especially in debugging data  Structures. Classes-------Prettyprinter ()     handle pretty-printing operations onto  a stream using a configured    set of formatting  Parameters. Functions---------Pformat ()     format a python object into a  pretty-printed representation ... "" "

Readers should read the source code in their spare time. It turns out that the source code in this standard library is of the best quality. Reading high-quality code is one way to improve the level of programming.

This article has been selected from the old Ziko python: Easy to get started, click this link to view the book on the website of the blog post.
650) this.width=650; "Src=" http://img.blog.csdn.net/20170331103620275?watermark/2/text/ ahr0cdovl2jsb2cuy3nkbi5uzxqvynjvywr2awv3mjawng==/font/5a6l5l2t/fontsize/400/fill/i0jbqkfcma==/dissolve/70/ Gravity/southeast "alt=" Picture description "title=" Picture description "style=" border:0px;vertical-align:middle; "/>
Want to get more good articles in time, you can search "blog point of View" or scan the QR code below and follow.
650) this.width=650; "src=" http://img.blog.csdn.net/20161128135240324 "alt=" Picture description "title=" Picture description "style=" border:0px; Vertical-align:middle; "/>


This article is from the blog of "Blog View blog", make sure to keep this source http://bvbroadview.blog.51cto.com/3227029/1912022

Python's powerful own modules-standard library

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.