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 efficient skills of Python

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

This article focuses on "what are the efficient skills of Python". Interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn "what are the efficient skills of Python"?

Clean up string input

Cleaning up user input problems applies to almost every program we may write. It is usually sufficient to convert characters to lowercase or uppercase, where you only need to use regularities, but for complex cases, there is a better way:

User_input = "This\ nstring has\ tsome whitespaces...\ r\ n" character_map = {ord ('\ n'):', ord ('\ t'):', ord ('\ r'): None} user_input.translate (character_map) # This string has some whitespaces... "

In the above example, you can see that the space characters "\ n" and "\ t" have been replaced by a single space, while "\ r" has been completely deleted. This is a simple example, but we can go a step further and use the unicodedata package and its combining () function to generate a broader mapping table that removes all accents from the string.

Iterator slice

If you try to get a slice of the iterator, the system reports TypeError, indicating that the generator object cannot be subscribed, but the solution is simple:

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

Using itertools.islice, we can create an islice object, which is the iterator that produces the desired elements. It is important to note, however, that this consumes all generator items until the slice starts, and it also consumes all items in our "islice" object.

Using itertools.islice we can create an islice object which is an iterator that produces desired items. It's important to note though, that this consumes all generator items up until the start of slice and also all the items in our islice object.

Skip the start of an iterable object

Sometimes there are unwanted rows of data in the files that need to be processed, but we are not sure about the number, such as comments in the code. At this point, itertools once again provides us with a concise solution:

String_from_file = "" / / Author:. / / License:. / Date:. Actual content... "" Import itertools for line in itertools.dropwhile (lambda line: line.startswith ("/ /"), string_from_file.split ("\ n"): print (line)

This code generates rows of data only after the initial comment section. This is useful if we only want to discard data at the beginning of the iterator without knowing that there is a specific amount.

Functions with only keyword arguments (kwargs)

Sometimes, using functions that only support keyword arguments can make your code clearer and easier to understand:

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

You only need to add a * parameter to the keyword parameter, and it can be easily implemented. Of course, if you still want to add the position parameter, you can add it before the * parameter.

Create objects that support with statements

We all know how to open a file or use a with statement to acquire a lock, but how can we do something similar ourselves? In general, we can use the _ _ enter__ and _ _ exit__ methods to implement the context manager protocol:

ClassConnection: def _ init__ (self):... Def _ _ enter__ (self): # Initialize connection... Def _ _ exit__ (self, type, value, traceback): # Close connection... WithConnection () as c: # _ _ enter__ () executes... # conn.__exit__ () executes

The above is the most common implementation, but there is a simpler way:

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

The above code snippet implements the content management protocol using the contextmanager manager decorator. When you enter the "with" block, execute the first part of the "tag" function (before "yield"), then yield, and finally the rest.

Save memory with _ _ slots__

If the program needs to create a large number of class instances, we will find that the program takes up a lot of memory. This is because Python uses dictionaries to represent the properties of class instances, which is fast to create, but memory-intensive. If memory is an issue you need to consider, then consider using _ _ slots__:

ClassPerson: _ _ 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 uses a fixed-size array (which takes up less memory) to store attributes instead of dictionaries, which greatly reduces the memory required for each instance. But there are some drawbacks to using _ _ slots__: we can't declare any new properties, so we can only use those in _ _ slots__. Similarly, classes with _ _ slots__ cannot use multiple inheritance.

Limit CPU and memory usage

If you don't want to optimize program memory or CPU usage, but want to limit it directly to a certain number, Python also has a library that meets the requirements:

Import signal import resource import os # To Limit CPU time def time_exceeded (signo, frame): print ("CPU exceeded...") RaiseSystemExit (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))

Here, we can set two options for maximum cpu elapsed time and maximum memory usage limit. For the cpu limit, we first get the soft limit and hard limit for that particular resource (RLIMIT_CPU), and then set it using the number of seconds specified by the parameter and the hard limit previously obtained.

Finally, we registered a signal to exit the system after the CPU time was exceeded. As for memory, we again get soft and hard limits and complete the configuration using setrlimit and hard limits with size parameters

Control what is imported

Some languages provide an explicit mechanism for exporting members (variables, methods, interfaces), such as Golang, which exports only members that begin with uppercase letters. But in Python, all objects are exported unless we use _ _ all__:

Def foo (): pass def bar (): pass _ _ all__ = ["bar"]

In the above code snippet, only the bar function is exported. In addition, if the value of _ _ all__ is empty, no functions are exported and AttributeError is reported when the module is imported.

Implement the comparison operator

If we were to implement all the comparison operators for a class one by one, you would find it troublesome, because there are a lot of methods to implement, such as _ _ lt__,__le__,__gt__, and _ _ ge__.

In fact, Python provides a convenient way to implement it through the functools.total_ordering decorator.

From functools import total_ordering @ total_ordering classNumber: def _ _ init__ (self, value): self.value = value def _ lt__ (self, other): returnself.value

< other.value def __eq__(self, other): returnself.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