laitimes

Python god with the thief slip, 9 practical tips to share to you [Chinese style animation] "Jiang Ziya" behind the brush screen, hiding the Chinese animation 100 years of insider [Chinese style animation] In addition to "Nezha", these conscience domestic animations should also be known by more people! 【Chinese style anime】 "Five Elements of the Misty Mountains" fire, but few people know its predecessor "Years City Glass Heart" A male protagonist holding a ten-meter knife died prematurely!

1

Organize string input

The problem of collating user input is extremely common during programming. Usually, converting characters to lowercase or uppercase is sufficient, and sometimes you can do this using the regular expression module "Regex". But if the problem is complex, there may be a better way to fix it:

In this example, you can see that both the space characters " n " and " t " are replaced with a single space , and " r " is deleted.

This is just a very simple example, we can go a step further and use the "unicodedata" package to generate a large remap table, and use the "combining()" in it to generate and map.

2

Iterator Slice

If you slice an iterator, a "TypeError" is returned, indicating that the generator object is not subscripted, but we can solve this problem with a simple solution:

We can use "itertools.islice" to create an "islice" object, which is an iterator that produces the items we want.

Note: This uses all the generator items before the slice, as well as all the items in the islice object.

3

Skip the beginning of an iterable object

Sometimes you have to deal with files that begin with unwanted lines, such as comments. "itertools" once again offers a simple solution:

This code prints only what follows the initial comments section. This is useful if we only want to discard the beginning of the iterable object (the line of comment at the beginning in this example) and don't know how long to make it.

4

Functions with only keyword arguments (kwargs)

When we use the following function, it is helpful to create functions that only require keyword arguments as input to provide a clearer function definition:

As you can see, adding a "*" before the keyword argument solves this problem. If we put some parameters before the "*" parameter, they are obviously positional parameters.

5

Create an object that supports the "with" statement

For example, we all know how to use the "with" statement to open a file or acquire a lock, but can we implement our own context expressions? Yes, we can use "enter" and "exit" to implement context management protocols:

This is the most common way to implement context management in Python, but there are simpler ways:

The above code implements the content management protocol using the contextmanager's manager decorator. The first part of the tag function (the part before yield) is executed when the with block is entered, then the with block is executed, and the rest of the tag function is executed at the end.

6

Save memory with "slots"

If you've ever written a program that creates a large number of instances of a class, you've probably noticed that your program suddenly requires a lot of memory.

That's because Python uses dictionaries to represent the properties of class instances, which makes it fast, but not very efficient at memory usage. Usually, this is not a serious problem. However, if your program is seriously affected by this, try "slots":

When we defined the "slots" property, Python did not use a dictionary to represent the property, but instead used a small fixed-size array, which greatly reduced the memory required for each instance.

Using "slots" also has some disadvantages: we can't declare any new properties, we can only use existing properties on "slots". Also, classes with "slots" cannot use multiple inheritance.

7

Limit "CPU" and memory usage

Instead of optimizing a program's memory or CPU usage, but limiting it directly to a certain number, Python also has a corresponding library that can do it:

As we can see, in the code snippet above, there is both an option to set the maximum CPU uptime and maximum memory usage limits.

When limiting the runtime of the CPU, we first get the soft and hard limits for that particular resource (RLIMIT_CPU), and then set them using the number of seconds specified by the parameter and the hard limit that was previously retrieved.

Finally, if the CPU runs longer than the limit, we will signal the system to exit. In terms of memory usage, we retrieve the soft and hard limits again, and set it using the "setrlimit" with the "size" parameter and the hard limits previously retrieved.

8

Controls what can and cannot be imported

Some languages have very obvious mechanisms for deriving members (variables, methods, interfaces).

For example, in Golang only members that begin with an uppercase letter are exported.

However, in Python, all members are exported (unless we use "all"):

In the above code, we know that only the "bar" function is exported. Similarly, we can make "all" empty so that nothing is exported, and when imported from this module, it will cause "AttributeError".

9

A simple way to implement comparison operators

Implementing all comparison operators for a class (such as lt, le, gt, ge) is tedious. Is there an easier way to do this? At this time, "functools.total_ordering" is a good helper:

How does this work?

We use the total_ordering decorator to simplify the process of sequencing class instances. We only need to define "lt" and "eq", which are the smallest set of operations needed to implement the rest of the operations (and here also reflects the role of the decorator - to fill in the blanks for us).

10

epilogue

Not all of the features mentioned in this article are necessary or useful in everyday Python programming, but some of them may come in handy from time to time, and they may also simplify some of the already lengthy and annoying tasks.

It should also be noted that all of these features are part of the Python Standard Library. And to me, some of these features don't seem like the standard content included in the standard library, so when you use Python to implement some of the features mentioned in this article, please refer to Python's standard library first, and if you can't find the feature you want, it may just be because you haven't tried your best to find it (if it really doesn't, it must also exist in some third-party libraries).

recommend:

<h1 class="pgc-h-arrow-right" data-track="123" > [Chinese Style Animation] "Jiang Ziya" behind the brush screen, hiding the inside story of Chinese animation for 100 years</h1>

<h1 class="pgc-h-arrow-right" data-track="124" > [Chinese Style Animation] In addition to "Nezha", these conscientious domestic animations should also be known by more people! </h1>

<h1 class="pgc-h-arrow-right" data-track="125" > [Chinese Style Animation] "Five Elements of the Misty Mountains" fire, but few people know its predecessor "Year City Glass Heart" A male protagonist with a ten-meter knife died prematurely! </h1>

statement

Source: 51CTO, artificial intelligence industry chain alliance recommended reading, does not represent the position of the artificial intelligence industry chain alliance, reprint please indicate, such as involving the copyright of the work, please contact us to delete or do related processing!