In this article, we will introduce some Python gods use the thief slippery skills, let a look into it! Welcome to collect to learn, like to praise support, welcome to chat.
Organize string input
The problem of organizing user input is common in programming. There are better ways 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 by several spaces, and "r" has been replaced. This is just a 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 the table.
Iterators (slices)
If you perform a simple operation on a returned object, you will be prompted to generate a "TypeError" under the object, but we can solve the problem with an object solution:
import itertools s = (range(50), 10, 20) # < object at 0x7f70fab88138> for val in s: ...
We can use "" to create an "islice", which is an iterator that generates the items we want. However, it is important to note that this operation uses the object and all the generator items of the object, all the items in the "islice" object.
Skipping the beginning of an object
Sometimes you have to deal with files that start with unwanted lines (e.g. comments). Once again, "itertools" provides a simple solution:
string_from_file = """ // Author: ... // License: ... // // Date: ... Actual content... """ import itertools for line in (lambda line: ("//"), string_from_file.split(" ")): print(line)
This code only prints what comes after the initial comment section. This is useful if we only want to discard the beginning part of the iterable object (the opening comment line in this example), but do not know how long we want this part to be.
Functions with keyword arguments only (kwargs)
When we use the following functions, it is helpful to create functions that require only keyword arguments as input to provide clearer function definitions:
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, the keyword argument is preceded by a "" will solve this problem. If we put certain parameters in the "" parameters before they are obviously positional parameters.
Creating objects that support "with" statements
For example, we all know how to open a file or get a lock using the "with" statement, but can we implement our own context expressions? Yes, we can implement the context management protocol using "enter" and "exit":.
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 a simpler way: the
from contextlib import contextmanager @contextmanager def tag(name): print(f"<{name}>") yield print(f"</{name}>") with tag("h1"): print("This is Title.")
The code above 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 you enter the with block, then the with block is executed, and finally the rest of the tag function is executed.
Save memory with "slots
If you've ever written a program that creates a large number of instances of some class, then you've probably noticed that your program suddenly requires a lot of memory. That's because Python uses dictionaries to represent the attributes of class instances, which makes it fast but not very efficient in terms of memory usage. Normally, this isn't a serious problem. However, if your program is seriously affected by it, 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 = phone
When we define the "slots" attribute, instead of using a dictionary to represent the attributes, Python uses small fixed-size arrays, which greatly reduces the amount of memory needed per instance. There are also some disadvantages to using "slots": we can't declare any new attributes, we can only use the existing attributes on the "slots". Also, classes with "slots" cannot use multiple inheritance.
Limit "CPU" and memory usage
If you don't want to optimize your program's memory or CPU usage, but rather just limit it to a certain number, Python has a library for that as well:
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.RLIMIT_CPU) (resource.RLIMIT_CPU, (seconds, hard)) (, time_exceeded) # To limit memory usage def set_max_memory(size): soft, hard = (resource.RLIMIT_AS) (resource.RLIMIT_AS, (size, hard))
We can see that the code snippet above contains options to set both the maximum CPU runtime and the maximum memory usage limit. When limiting the CPU's runtime, we first get the soft and hard limits for that particular resource (RLIMIT_CPU), and then set them using the number of seconds specified via the parameter and the previously retrieved hard limits. Finally, if the CPU runs longer than the limit, we signal a system exit. For memory usage, we retrieve the soft and hard limits again and set it using 'setrlimit' with the 'size' parameter and the previously retrieved hard limit.
Control what can/cannot be imported
Some languages have very obvious mechanisms for exporting members (variables, methods, interfaces), e.g., in Golang only members that start with a capital letter are exported. However, in Python, all members are exported (unless we use "all"):
def foo(): pass def bar(): pass __all__ = ["bar"]
In this code above, we know that only the 'bar' function is being exported. Again, we can leave 'all' empty so that nothing is exported, which will cause an 'AttributeError' when importing from this module.
A Simple Way to Implement Comparison Operators
Implementing all the comparative similarities (e.g. lt , le , gt , ge) for a class is tedious. Is there an easier way to do this? At such times, "functools.total_ordering" is a good helper:
from functools import total_ordering @total_ordering class Number: def __init__(self, value): = value def __lt__(self, other): return < def __eq__(self, other): return == print(Number(20) > Number(3)) print(Number(1) < Number(5)) print(Number(15) >= Number(15)) print(Number(10) <= Number(2))
How exactly does it work here? We use the 'total_ordering' decorator to simplify the implementation of ordering class instances. All we need to do is define 'LT' and 'equivalent', which are the smallest sets needed to implement the rest of the operations (and here is where the decorator comes in - manipulating the whitespace for us).
concluding remarks
Not all of the features in this article are specific to or useful in everyday Python programming, but some may not come in handy from time to time, and they may be simple tasks that would be lengthy and tiresome. It should also be noted that all of these features are part of the Python standard library. If you can't find what you're looking for, it's probably just because you haven't looked hard enough (and if you haven't, it's certainly in some of the available libraries).
technical exchange
Feel free to republish, bookmark, and like something to support it!
To this point this article on the sharing of Python's 9 practical tips on this article, more related Python skills content please search my previous posts or continue to browse the following related articles I hope you will support me more in the future!