Share with you 9 practical tips for Python masters

The Python video tutorial column will try to introduce some tips that are not mentioned in other articles. These tips are also what I usually use. Let us find out!

Organizing string input
The problem of organizing user input is very common in the programming process. Normally, it is enough to convert characters to lowercase or uppercase. Sometimes you can use the regular expression module "Regex" to accomplish this. But if the problem is complicated, there may be a better way to solve it:

user_input = "This 

string has  some whitespaces... 

" 

character_map = {
    
     

    ord(  

 ) :    , 

    ord(     ) :    , 

    ord(  

 ) : None 

} 

user_input.translate(character_map)  # This string has some whitespaces...复制代码

In this example, you can see that the space characters "n" and "t" have been replaced with a single space, and the "r" has been deleted. This is just a very simple example. We can go further and use the "unicodedata" package to generate a large remapping table, and use the "combining()" in it to generate and map, we can

Iterator slice (Slice)
If you slice the iterator, it will return a "TypeError", indicating that the generator object does not have a subscript, 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 use "itertools.islice" to create an "islice" object, which is an iterator that can generate the items we want. But it should be noted that this operation uses all the generator items before the slice and all the items in the "islice" object.

Skip the beginning of iterable objects
Sometimes you have to deal with files that start with unwanted lines (such as comments). "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 only prints the content after the initial comment. This method is useful if we only want to discard the beginning part of the iterable object (in this example, the beginning comment line), but don't know how long this part is.

Functions that contain only keyword arguments (kwargs)
When we use the following functions, it is helpful to create a function that only requires keyword arguments as input to provide a clearer function definition:

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, adding a "" before the keyword parameter can solve this problem. If we put some parameters before the "" parameter, they are obviously positional parameters.

Create objects that support 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 expression? Yes, we can use "enter" and "exit" to implement the context management protocol:

class Connection: 

    def __init__(self): 

        ... 

    def __enter__(self): 

        # Initialize connection...      def __exit__(self, type, value, traceback): 

        # Close connection...  with Connection() as c: 

    # __enter__() executes      ... 

    # conn.__exit__() executes复制代码

This is the most common way to implement context management in Python, but there is an easier way:

from contextlib import contextmanager 

@contextmanager 

def tag(name): 

    print(f"<{name}>") 

    yield 

    print(f"") 

with tag("h1"): 

    print("This is Title.")复制代码

The above code uses the manager decorator of contextmanager to implement the content management protocol. When entering the with block, the first part of the tag function (the part before the yield) has been executed, and then the with block is executed, and finally the rest of the tag function is executed.

Use "slots" to save memory
If you have ever written a program that creates a large number of instances of a certain class, you may have noticed that your program suddenly requires a lot of memory. That's because Python uses a dictionary to represent the attributes of a class instance, which makes it fast, but the memory usage efficiency is not very high. Normally, this is not a serious problem. However, if your program is severely affected as a result, try "slots":

class Person: 

    __slots__ = ["first_name", "last_name", "phone"] 

    def __init__(self, first_name, last_name, phone): 

        self.first_name = first_name 

        self.last_name = last_name 

        self.phone = phone复制代码

When we define the "slots" attribute, Python does not use a dictionary to represent the attributes, but uses a small fixed-size array, which greatly reduces the memory required for each instance. There are also some disadvantages to using "slots": we cannot declare any new attributes, we can only use the existing attributes on "slots". Also, classes with "slots" cannot use multiple inheritance.

Limiting "CPU" and memory usage
If you don't want to optimize the program's usage of memory or CPU, but want to directly limit it to a certain number, Python also has a corresponding library that can do it:

import signal 

import resource 

import os 

# To Limit CPU time 

def time_exceeded(signo, frame): 

    print("CPU exceeded...") 

    raise SystemExit(1) 

def set_max_runtime(seconds): 

    # Install the signal handler and set a resource limit 

    soft, hard = resource.getrlimit(resource.RLIMIT_CPU) 

    resource.setrlimit(resource.RLIMIT_CPU, (seconds, hard)) 

    signal.signal(signal.SIGXCPU, time_exceeded) 

# To limit memory usage 

def set_max_memory(size): 

    soft, hard = resource.getrlimit(resource.RLIMIT_AS) 

    resource.setrlimit(resource.RLIMIT_AS, (size, hard))复制代码

We can see that in the above code snippet, there are options to set the maximum CPU runtime and maximum memory usage limit at the same time. When limiting the running time of the CPU, we first obtain the soft limit and the hard limit of the specific resource (RLIMIT_CPU), and then use the number of seconds specified by the parameter and the previously retrieved hard limit to set it. Finally, if the running time of the CPU exceeds the limit, we will signal the system to exit. In terms of memory usage, we retrieve the soft limit and the hard limit again, and use the "setrlimit" with the "size" parameter and the previously retrieved hard limit to set it.

Control what can/cannot be imported.
Some languages ​​have very obvious mechanisms to export members (variables, methods, interfaces). For example, in Golang, only members starting with a capital letter are exported. However, in Python, all members will be exported (unless we use "all"):

def foo(): 

    pass 

def bar(): 

    pass 

__all__ = ["bar"]复制代码

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

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

from functools import total_ordering 

@total_ordering 

class Number: 

    def __init__(self, value): 

        self.value = value 

    def __lt__(self, other): 

        return self.value < other.value 

    def __eq__(self, other): 

        return self.value == other.value 

print(Number(20) > Number(3)) 

print(Number(1) < Number(5)) 

print(Number(15) >= Number(15)) 

print(Number(10) <= Number(2))复制代码

What is the working principle here? We use the "total_ordering" decorator to simplify the process of sorting class instances. We only need to define "lt" and "eq", they are the smallest set of operations needed to implement the rest of the operations (here also reflects the role of the decorator-to fill the gap for us).

Conclusion
Not all the functions mentioned in this article are necessary or useful in daily Python programming, but some of them may come in handy from time to time, and they may also simplify some already lengthy and annoying tasks. . It should also be pointed out that all these functions are part of the Python standard library. In my opinion, some of these functions do not seem to be like the standard content included in the standard library, so when you use Python to implement some of the functions mentioned in this article, please refer to the Python standard library first. If you can’t find what you want The function may just be because you haven't tried your best to find it (if it doesn't, then it must also exist in some third-party libraries).
This article comes from the php Chinese website python video tutorial column: https://www.php.cn/course/list/30.html

Guess you like

Origin blog.csdn.net/Anna_xuan/article/details/109602167
Recommended