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 Python development skills?

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

Share

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

This article mainly introduces "what are the Python development skills". In the daily operation, I believe many people have doubts about what Python development skills they have. The editor consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful for you to answer the doubts about "what Python development skills do you have?" Next, please follow the editor to study!

1. How do I view the source code while running?

Looking at the source code of this function, we usually use IDE to do this.

For example, in PyCharm, you can use the source code of the Ctrl + mouse input function.

What if there is no IDE?

When we want to use a function, how do we know which parameters the function needs to receive?

When we encounter a problem when using a function, how to solve the problem by reading the source code?

Currently, we can use inspect instead of IDE to help you do these things

Inspect.getsource: returns the text of the source code of the object.

The inspection module provides several useful functions to help get information about active objects, such as modules, classes, methods, functions, backtracking, frame objects, and code objects.

There are four main services provided by this module:

Type check

Get the source code

Check classes and functions

Check the interpreter stack.

two。 The fastest way to view the package path

When you import a package or module using import, Python will look in some directories, and these directories are in order of priority, which we will usually look at using sys.path.

Is there a faster way?

Here I would like to introduce a more convenient method than above, which can solve one-line command:

From the output, you can see that the path to this column will be more complete than sys.path (the directory that contains the user environment).

3. Write a nested loop as one line

We often use the following nested loop code:

There are only three for loops, and there may be more layers in the actual coding.

Such code is not readable, people don't want to write it, and there is a better way to write it.

Here, I introduce a common writing method that uses the itertools library to implement more elegant and readable code.

4. How to use printout logs

Many people like to use printing to debug code and record the running process of the program.

However, printing only outputs the content to the terminal and cannot be retained in the log file, which is not conducive to troubleshooting.

If you are keen to use printing to debug your code (although this is not a best practice), record the process of running the program, and the printing usage described below may be useful to you.

Print it as a function in Python 3, because it can take more arguments, so the function itself becomes more powerful.

The code is as follows:

5. How to quickly calculate the running time of functions

To calculate the run time of a function, you can do this

You will see that several lines of code have been written to calculate the run time of the function.

Is there a way to calculate the elapsed time more easily? Yes, use a built-in module called timeit.

It only takes a single line of code to use the

The results are as follows:

2222210.020059824

6. Use built-in caching mechanisms to improve efficiency

Caching is a method to store quantitative data to meet the needs of subsequent collection, in order to speed up the speed of data collection.

The data generation process may require operations such as computation, regularization, and remote acquisition. If the same data needs to be used multiple times, each regeneration is a waste of time.

Therefore, if data obtained through operations such as calculations or remote requests are cached, subsequent data acquisition requirements will be accelerated.

To meet this requirement, Python 3.2 + provides us with a mechanism that is easy to implement without requiring you to write such logic code.

This mechanism is implemented in the lru_cache decorator of the functool module.

Parameter explanation:

Maxsize: the maximum number of results that can be cached by this function call. If it is None, there is no limit. When set to the power of 2, the performance is the best.

Type: if True, calls of different parameter types are cached separately.

For example:

The output is as follows, and you can see that the second call does not execute the function body, but returns the result directly to the cache:

Calculating: 1 + 233calculating: 2 + 35

The following is the classic Fibonacci sequence, and when you specify a larger n, there will be a lot of repeated calculations

You can now use the timeit described in point 6 to test how much efficiency can be improved.

If you do not use lru_cache, the run time is 31 seconds:

After using lru_cache, it was too fast, so I adjusted the value of n from 30 to 500, but even so, the run time was only 0.0004 seconds. The increase in speed is very significant.

7. Tips for executing code before the program exits

With the built-in module atexit, you can easily register and exit features.

No matter where you cause the program to crash, it performs the functions you have registered. Examples are as follows:

The results are as follows:

If the clean () function has parameters, you can call atexit.register (clean_1, parameter 1, parameter 2, parameter 3 = "xxx") without a modifier.

You may have other ways to deal with this requirement, but it is more elegant, more convenient, and easier to extend than not using atexit.

However, there are still some limitations to using atexit, such as:

If the program is killed by an unprocessed system signal, the registered function will not perform properly.

If a serious Python internal error occurs, the function you registered cannot be executed properly.

If os._exit () is called manually, the registered function cannot be performed properly.

8. How do I turn off the exception context?

When you handle an exception, due to improper handling or other problems, when another exception is thrown, the thrown exception will also carry the original exception information.

Read it again and you will understand it now.

Like this.

You can see two exception messages from the output:

If an exception is thrown in an exception handler or finally block, by default, the exception mechanism works implicitly to append the previous exception as the _ _ context__ attribute of the new exception.

This is the automatic association of exception contexts enabled by Python by default.

If you want to control this context yourself, you can add a from keyword (the limitation of from is that the second expression must be another exception class or instance.) To indicate which exception caused your new exception.

The output is as follows

Of course, you can also use the with_traceback () method to set the _ _ context__ property of the exception, which can also better display the exception information in backtracking.

Finally, do you want to completely turn off this mechanism for automatically associating exception contexts? What else can we do?

Can be used to raise... Never, from the following example, there is no original exception

9. Implement calls with similar delays

There is a mechanism for delaying calls in Golang. The keyword is defer, as shown below

The call to myfunc will be completed before the function returns, and even if you write a call to myfunc on the first line of the function, this is a delayed call. The output is as follows

AB

So is there such a mechanism in Python?

Of course, but it's not as simple as Golang.

We can use the Python context manager to achieve this effect

The output is as follows

AB

10. How to read large files by stream

Use with... Open... You can read data from a file, which is familiar to all Python developers.

However, if it is not used properly, it will also cause a lot of trouble.

For example, when you use the read feature, Python loads the contents of the file into memory all at once. If the file has 10 GB or more, the computer will consume a very large amount of memory.

For this problem, you might consider using readline as a generator to return row by line.

However, if the contents of this file are on one line, you will still read everything at once for 10 GB per line.

The most elegant solution is to use the read method to specify that only a fixed size of content is read at a time. For example, in the following code, only 8kb is returned at a time.

The above code is functionally fine, but it still looks a little swollen.

Using partial and iterative functions, you can optimize your code like this

At this point, the study of "what are the Python development skills" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

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