Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the practical skills of Python

2025-03-29 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly explains "what Python practical skills are". The explanation in this article is simple and clear, easy to learn and understand. Please follow the ideas of Xiaobian and go deep into it slowly to study and learn "what Python practical skills are" together.

Sort string input

The problem of organizing user input is extremely common in programming. Usually, converting characters to lowercase or uppercase is enough, sometimes you can use the regular expression module "Regex" to do this. But if the problem is complex, 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 spaces "n" and "t" have been replaced with single spaces, and the "r" has been deleted. This is just a very simple example, we can go further, using the "unicodedata" package to generate a large remapping table, and using the "combining()" to generate and map, we can

Iterator Slice

If we slice the iterator, we will return a TypeError, indicating that the generator object has no subscript, but we can solve this problem with a simple solution:

import itertools s = itertools.islice(range(50), 10, 20) # for val in s: ...

We can use itertools.islice to create an islice object, which is an iterator that produces the items we want. Note, however, that this operation uses all generator items prior to slicing, as well as all 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 prints only what follows the initial comment section. This is useful if we want to discard only the first part of the iterable object (in this case, the first comment line), but we don't know how long we want that part to be.

Functions with keyword arguments only (kwargs)

When we use the following functions, it helps 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, adding an "*" before the keyword parameter solves this problem. If we put some parameters before the "*" parameter, they are obviously positional parameters.

Creating objects that support the "with" statement

For example, we all know how to open a file or acquire a lock using a "with" statement, but can we implement our own contextual expressions? Yes, we can implement context management protocols 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 are simpler ways:

from contextlib import contextmanager @contextmanager def tag(name): print(f"") yield print(f"") with tag("h2"): print("This is Title. ")

The above code implements the content management protocol using the manager decorator of contextmanager. The first part of the tag function (before yield) is executed when entering 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 a class, you've probably noticed that your program suddenly needs a lot of memory. That's because Python uses dictionaries to represent attributes of class instances, which makes it fast but less memory efficient. Usually, this is not a serious problem. However, if your program is severely affected by this, 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 doesn't use dictionaries to represent attributes, but small fixed-size arrays, which greatly reduces the memory required for each instance. There are also some disadvantages to using "__slots__": we cannot declare any new properties, we can only use existing properties on "__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 want to limit it directly to a certain number, Python has a library that does the same:

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))

As you can see, in the code snippet above, there are options for setting both maximum CPU runtime and maximum memory usage limits. When limiting CPU runtime, we first obtain 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 retrieved previously. Finally, if the CPU runs longer than the limit, we signal system 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 limit retrieved earlier.

Controls what can/cannot be imported

Some languages have very obvious mechanisms for exporting members (variables, methods, interfaces), such as Golang, where only members starting with capital letters are exported. However, in Python, all members are exported (unless we use "__all__"):

def foo(): pass def bar(): pass __all__ = ["bar"]

In the code above, we know that only the "bar" function is exported. Similarly, we can leave "__all__" empty so that nothing is exported, which causes an AttributeError when importing from this module.

Simple way to implement comparison operators

Implementing all the comparison operators (such as__lt__ , __le__ , __gt__ , __ge__) for a class is cumbersome. Is there an easier way to do this? In this case, 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)

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report