Some programming suggestions for Python beginners
This article mainly introduces some programming suggestions for Python beginners, including collection initialization and GIL understanding. For more information, see
Python is a very expressive language. It provides us with a huge standard library and many built-in modules to help us quickly complete our work. However, many people may be lost in the functions it provides, cannot make full use of the standard library, excessive emphasis on single-line scripts, and misunderstanding of the basic structure of Python. This article is an incomplete list of some traps that beginners may fall.
I do not know the Python version
This is a problem that occurs repeatedly on StackOverflow. Many people can write code that works perfectly on a specific version, but install different versions of Python on their own systems. Make sure that you know the Python version you are using.
You can view the Python version through the following code:
?
1 2 3 |
$ Python -- version <STRONG> Python 2.7.9 </STRONG> |
Do not use version Manager
Pyenv is an excellent tool for managing different Python versions, but unfortunately it only works on * nix systems. On Mac, you can simply install it through brew install pyenv. on Linux, there is also an automatic installation program.
Indulge in a single program
Many people are keen on the excitement of a program. Even if their one-line solution is less efficient than a multi-line solution, they boast.
In Python, a row of programs essentially means complex derivation with multiple expressions. For example:
?
1 |
L = [m for a, B in zip (this, that) if B. method ()! = B for m in B if not m. method (a, B) and reduce (lambda x, y: a + y. method (), (m, a, B)] |
Honestly, I fabricated the above example. But I see many people write similar code. Such code becomes hard to understand in a week. If you want to do something slightly complex, such as simply adding an element to a list or set based on conditions, you may make mistakes.
Single-line code is not an achievement. Yes, they may seem flexible, but not an achievement. Imagine that it is like stuffing everything into your closet while you are cleaning the room. Good code should be clean, easy to read, and efficient.
Initialize a set in the wrong way
This is a more subtle issue and may surprise you. Set derivation is like list derivation.
?
1 2 3 |
>>>{ N for n in range (10) if n % 2 = 0} {0, 8, 2, 4, 6} >>> Type ({n for n in range (10) if n % 2 = 0 }) |
The above is an example of the Set derivation. A set is like a list and a container. The difference is that there cannot be any duplicate values in a collection, and they are unordered. People often mistakenly think that {} can initialize an empty set. But it does not actually Initialize an empty dictionary.
?
1 2 3 |
>>> {} {} >>> Type ({}) |
If you want to initialize an empty set, you can simply call the set () method.
?
1 2 3 |
>>> Set () Set () >>> Type (set ()) |
Note that an empty set is expressed in combination with set (), but a set containing some elements must be represented in curly brackets.
?
1 2 3 4 5 6 7 8 9 |
>>> S = set () >>> S Set () >>> S. add (1) >>> S {1} >>> S. add (2) >>> S {1, 2} |
This is the opposite of intuition, because you expect something similar to set ([1, 2.
Misunderstanding GIL
GIL (Global interpreter lock) means that only one thread can be running at any time point in the Python program. This means that when we create a thread and want it to run in parallel, it will not. The actual task of the Python interpreter is to quickly switch between different running threads. However, this is just a simple explanation of what actually happens, and the actual situation is much more complicated. There are many types of parallel running instances, such as various libraries that are essentially C-extended. But it does not execute Python code in parallel most of the time. In other words, the threads in Python are not like those in Java or C ++.
Many people will try to justify Python, saying that these are real threads. This is true, but it cannot change the fact that the way Python processes threads is different from what you expect. The Ruby language also has the same situation (Ruby also has an interpreter lock ).
The specified solution is to use the multiprocessing module. The multiprocessing module provides the Process class, which is a good coverage of fork. However, the fork process is much more expensive than a thread, so you may not see performance improvement every time, because different processes need to do a lot of work to coordinate with each other.
However, this problem does not exist in every Python implementation version. For example, a Python Implementation of PyPy-stm tries to get rid of GIL (not yet stable ). The Python implementation on other platforms, such as JVM (Jython) or CLR (IronPython), has no problems with GIL.
In short, be careful when using the Thread class. What you get may not be what you want.
Use vintage classes
In Python 2, there are two types of classes: "old-fashioned" class and "new-style" class. If you use Python 3, you use the "new" class by default. To ensure that the "new" class is used in Python2, you need to make every new class you create inherit the object class, and the class cannot inherit the built-in type, such as int or list. In other words, if your base class and class do not inherit other classes, they always need to inherit the object class.
?
1 2 |
Class MyNewObject (object ): # Stuff here |
These "new" classes solve the fundamental defects of some old classes, which we do not need to know in depth. However, if someone is interested, they can find relevant information in the relevant documents.
Iteration by mistake
For beginners of this language, the following code is very common:
?
1 2 |
For name_index in range (len (names )): Print (names [name_index]) |
In the above example, there is no need to call the len function, because list iteration is actually much simpler:
?
1 2 |
For name in names: Print (name) |
There are also a bunch of other tools to help you simplify iteration. For example, you can use zip to traverse two lists at the same time:
?
1 2 |
For cat, dog in zip (cats, dogs ): Print (cat, dog) |
If you want to consider both the index and value of the List variables, you can use enumerate:
?
1 2 |
For index, cat in enumerate (cats ): Print (cat, index) |
There are also many useful functions in itertools for you to choose from. However, please note that using the itertools function is not always the correct choice. If a function in itertools provides a very convenient solution to the problem you are trying to solve, such as flattening a list or creating an arrangement of its content based on the given list, use it. But don't adapt to a part of your code just because you want it.
Problems caused by misuse of itertools occur too frequently, so that a highly respected Python contributor on StackOverflow has contributed an important part of their data to solve these problems.
Use variable default parameters
I have seen the following code multiple times:
?
1 2 3 |
Def foo (a, B, c = []): # Append to c # Do some more stuff |
Never use a variable default parameter. You can use the following code instead:
?
1 2 3 4 5 |
Def foo (a, B, c = None ): If c is None: C = [] # Append to c # Do some more stuff |
Rather than explaining what the problem is, it is better to show the impact of using variable default parameters:
?
1 2 3 4 5 6 7 8 9 10 11 |
In [2]: def foo (a, B, c = []): ... C. append () ... C. append (B) ... Print (c) ... In [3]: foo (1, 1) [1, 1] In [4]: foo (1, 1) [1, 1, 1, 1] In [5]: foo (1, 1) [1, 1, 1, 1, 1, 1] |
The same variable c is repeatedly referenced in every function call. This may have some unexpected consequences.
Summary
These are just some problems that people who are new to Python may encounter. However, please note that the possible problems are far from that. However, another drawback is that people use Python like Java or C ++ and try to use Python in the way they are familiar with it. As a continuation of this article, I try to go deep into something, such as the super function of Python. Let's look at the class method, static method, and _ slots.