Python practical skills summary

Finishing string input

Problem finishing the user input is extremely common in the programming process. Typically, the characters are converted to lowercase or uppercase enough, sometimes you can use regular expressions module "Regex" get the job done. However, if the issues are complex, there may be better ways to solve:
Here Insert Picture Description
In this example, you can see the space character "n" and "t" are replaced with a single space, "r" have been deleted. This is just a very simple example, we can go further, using "unicodedata" package generates a large remap table, and use them, "combining ()" were generated and mapping, we can

Iterator slice (Slice)

If you slice a pair of iterators will return a "TypeError", suggesting that there is no index generator object, but we can use a simple solution to solve this problem:

import itertools

s = itertools.islice(range(50), 10, 20)  # <itertools.islice object at 0x7f70fab88138>
for val in s:
    ...

We can create a "islice" object using the "itertools.islice", the object is an iterator, you can produce items we want. But note that all builder items before the operation to use slices, as well as all "islice" object.

Skip the beginning iterables

Sometimes you have to deal with some files to unwanted lines (such as comments) begin with. "Itertools" once again provides a simple solution:

string_from_file = """
// Author: ...
// License: ...
//
// Date: ...
Actual content...
"""

import itertools

for line in itertools.dropwhile(lambda line: line.startswith("//"), string_from_file.split("
")):
    print(line)

This code will print only the content after the initial comments section. If we just want to give up the beginning (for the beginning of the comment line in this example) iterables, but do not know how long this part of the time, this method is very useful.

Only contains the keyword arguments of the function (kwargs)

When we use the following function, only need to create a keyword as a function of input parameters to provide a clearer definition of the function, it can be helpful:

def test(*, a, b):
    pass

test("value for a", "value for b")  # TypeError: test() takes 0 positional arguments...
test(a="value", b="value 2")  # Works...

As you can see, plus a "before keyword arguments " can solve this problem. If we put some parameters " before" argument, which apparently is the location parameter.

Creating support "with" statement of objects

For example, we all know how to use the "with" statement to open a file or acquire a lock, but we can implement your own context expression it? Yes, we can use the " enter " and " exit " to implement context management protocol:
Here Insert Picture Description
This is the Python, the most common way to implement context management, but there is an easier way:
Here Insert Picture Description
Manager decorative use of the above code of contextmanager implements content management protocol. When entering the block with a first portion (the portion before yield) tag function has been performed, then the block is performed only with the last execution of the rest of the tag functions.

With " slots " to save memory

If you've ever written a large number of instances of a program to create some sort, then you may have noticed that your program suddenly need a lot of memory. That is because Python use a dictionary to represent the attributes of a class instance, which makes it very fast, but the memory use efficiency is not high. Under normal circumstances, this is not a serious problem. However, if your program is therefore severely affected may wish to try " slots ":
Here Insert Picture Description
when we define the " slots when" attribute, Python does not use a dictionary to represent the properties, but the use of small fixed-size array, which greatly reduces the memory required for each instance. The use of " slots " also has some drawbacks: We can not declare any new properties, we can only use the " slots " on existing properties. Moreover, with the " slots like" can not be used multiple inheritance.

Limit "CPU" and memory usage

If you do not want the optimizer to memory or CPU usage, but want to limit its direct digital a determined, Python also has a corresponding library can do:
Here Insert Picture Description
We can see in the above code snippet, at the same time It contains sets the maximum CPU time and memory options for maximum usage limits. When the CPU running time limit, we first get that particular resource (RLIMIT_CPU) of soft and hard limits, then the number of seconds specified by the parameters previously retrieved and hard limit to be set. Finally, if the CPU running time exceeds the limit, we will send a signal to exit the system. In terms of memory usage, we once again retrieve the soft and hard limits, and with the use of "size" parameters "setrlimit" and previously searched hard limit to set it up.

Control may / may not import anything

Some languages have a very clear mechanism to export the members (variables, methods, interfaces), for example, is exported only to members start with a capital letter in Golang in. However, in Python, all members will be exported (unless we use " all "):
Here Insert Picture Description

In the above code, we know that only "bar" function is derived. Similarly, we can make " all " is empty, so you do not export anything, when imported from this module will cause "AttributeError."

Simple way to implement comparison operators

All class implements a comparison operator (e.g., lt , Le , gt , GE ) is very cumbersome. There are easier ways to do that? This time, "functools.total_ordering" is a good helper:
Here Insert Picture Description
the principle here is what is it? We simplify the implementation process of the sort of instance of a class with "total_ordering" decorator. We only need to define " lt " and " eq " on it, which is to achieve a minimum set of operations required for the operation of the rest (here also reflects the role of decorator - for us to fill in the blanks).

Epilogue

Not all of the features mentioned in this article are necessary or useful in everyday Python programming, but some of these features might come in handy from time to time, but they may also simplify some had very lengthy and frustrating task. It should also be noted that all of these features are part of the Python standard library. And in my opinion, some of these features does not seem like standard content standards contained in the library, so when you use Python implement some features mentioned in this article, please refer to the Python standard library, if you can not find what you want function, may be just because you do not try to find (if it is not, then it must also be present in some third-party libraries).

Published 38 original articles · won praise 1 · views 2199

Guess you like

Origin blog.csdn.net/wulishinian/article/details/102975310