During the National Day holiday ,Python3.9 Officially launched , The major IT The platform and many we media have opened fire , Hot push Python3.9 New features . However , In addition to the self entertainment of the media , Almost all programmers are indifferent to this . I even think , Every time the version is upgraded Python The threshold of learning , It scares beginners .
Simple and elegant , yes Python Founder Guido · Van rosum ( Uncle GUI ) When the mountain gate was opened, it was Python Established Philosophy . Now? ,Pyton Obviously, the development of this principle has deviated from this principle : Whether it's useful or not , Whatever other family has , All income ; Whether it's suitable or not , As long as it can fill the facade , Bring it all . This situation is just like that in those years Pandas The father of Wes · McKinney faces Pandas When the rapid expansion of the expression of helplessness :“Pandas It's a departure from the simplicity and ease of use that I originally expected , Becoming more and more bloated and uncontrollable .”
once , I like... Very much Python. today , This love is still there , But a little bit more calm and rational . More than ten years of company , From obscurity to popularity ,Python Finally in the software rankings occupy a prominent position . In the expansion storm sweeping the software industry , stay Python Continuous version upgrade , But I saw a dangerous shift :Python From simplicity to bloated , From practical to vulgar .
For a long time , Free today , Make complaints about it Python New language features for . The following is a summary of the causes of Python The top ten dangerous turning points , In no particular order .
About from Py3.5 Start , Until the latest Py3.9, Feeling Python The language project team is doing one thing : Static type check . To implement type checking , They launched typing modular , Defined a lot of application rules . Corresponding , A number of static type checking tools came into being , such as Mypy、Pylint perhaps Pyflakes,PyCharm It can also integrate these tools well . Regarding this , I just want to say :Python It's a dynamic language ? Since it's a dynamic language , Then you check the wool ? Even if the inspection passes , It can run like a compiled language ? It's just an illusion , Please don't use the idea of other languages to kill the simple Python.Python The pursuit is to solve problems in the simplest way , Rather than creating trouble , And then solve the problem .Python Push static type checking , It's just catering to those integrated development environments (IDE), At the same time to meet the unknown programmer's sense of achievement and vanity .
When one has 5 Years of working experience Python When a programmer reads the following code , What will it feel like ?
>>> name: str
>>> age: int = 18
>>> gilrfriends: list = [' Audrey Hepburn · Hepburn ', ' Camilla · Beller ', ' Angelina · Julie ']
I believe he will say , Oh my god , What is it? ? yes Python Do you ? you 're right , This is really Python. It looks like the type of the variable is specified , But even if you assign a string to a variable of type list as follows , The runtime will not issue any prompts or warnings .
>>> gilrfriends: list = ' Audrey Hepburn · Hepburn , Camilla · Beller , Angelina · Julie ' # Turn left with the right turn light
>>> gilrfriends
' Audrey Hepburn · Hepburn , Camilla · Beller , Angelina · Julie '
You see , Turn left with the right turn light , It's the same as before . What's the use of such an operation ? It's just to make IED Or the type checker knows the type of the variable . Tools are meant for programmers , Ok now , You have to serve the tools first . Bad review !
I've been looking for a way to define the type of function parameters , In order to avoid unexpected situations when the program is running . Limited by Python The mechanism of , Most of the time I can only use assertions (assert) Limit the type of arguments within a function , At the same time as much as possible in __doc__ The type and meaning of parameters are described in detail , Just like the code below .
def sphere(center, radius, color, slices=90):
""" Drawing a sphere
center - Its coordinates , The length is 3 A tuple or list of
radius - radius , floating-point
color - Vertex color , character string
slices - The number of spherical slices ( The larger the value, the more refined ), integer
"""
assert isinstance(center, (tuple, list)) and len(center)==3, ' Expected parameters center It's a length of 3 A tuple or list of '
print('Hello')
return True
Now? , If according to Python The way the steering committee advocates , The code above should be written in the following style .
from typing import Union
def sphere(center:Union[tuple,list], radius:float, color:str, slices:int=90) -> bool:
""" Drawing a sphere
center - Its coordinates , The length is 3 A tuple or list of
radius - radius , floating-point
color - Vertex color , character string
slices - The number of spherical slices ( The larger the value, the more refined ), integer
"""
print('Hello')
return True
It looks like everything is perfect , But it turned out to be a pity . The type annotation of this function and parameter is just a comment , Look and feel : No matter what type of parameter you enter , As long as the quantity is enough 3 A or 4 individual , Can be executed . The only effect is to reduce the readability of the code , The original four parameters can be seen at a glance , Now it costs 20 Seconds to identify . There will be no type validation ( Unless you use a type checker ), And there's no length check . If you want these features , It's up to you .
Any programming language is constantly updated and expanded in the development of ,Python No exception . Tell the truth ,Python Some grammatical extensions of , It's still very subtle and necessary , such as Py3.8 The introduced walrus operator (:=), It's a typical example . Before introducing the walrus operator , If you want to make a deficiency 16 Bit long string s use # Make up 16 position ( If it is greater than or equal to 16 Bits are output as is ), It is usually written as follows .
>>> s = 'Hello Wold'
>>> s + '#'*(16-len(s)) if len(s) < 16 else s
'Hello Wold######'
This code computes the string twice s The length of , obviously , This is not an efficient code . But if you use a temporary variable to hold the string s The length of , It's not elegant enough . The walrus operator was born to solve this kind of problem .
>>> s = 'Hello Wold'
>>> s + '#'*(16-c) if (c:=len(s)) < 16 else s
'Hello Wold######'
unfortunately , Not all extensions are as wonderful as walrus operators , Even a large part of the expansion does not show enough necessity and irreplaceable , It's just bringing more confusion to programmers . such as ,Py3.9 New dictionary merge (|) And update (|=) Operator , In this column .
>>> a = {
'x':1, 'y':2}
>>> b = {
'y':3, 'z':4}
>>> a | b # Return to a new dictionary
{
'x': 1, 'y': 3, 'z': 4}
>>> a |= b # take b Merge into a in
>>> a
{
'x': 1, 'y': 3, 'z': 4}
Serious doubt Python The team forgot the dictionary and there was a update() Method can implement the functions of these two new operators .
>>> a = {
'x':1, 'y':2}
>>> b = {
'y':3, 'z':4}
>>> a.update(b)
>>> a
{
'x': 1, 'y': 3, 'z': 4}
Some might say , Even if dictionary update operator (|=) and update() The functions overlap completely , Dictionary merging operators (|) It's a new dictionary , and update() Changed the original dictionary . For those who hold this idea , I can only quietly remind you ,Python There's been a solution to this .
>>> {
**a, **b}
{
'x': 1, 'y': 3, 'z': 4}
Lots of built-in functions or methods , Of course, it can bring more convenience to programmers , But it also makes the system bloated , At the same time, it increases the difficulty of introduction , Make the learning curve steep . How to balance this scale , It's a matter of opinion . in my opinion , There are more and more functions and methods , Not only is it against Python The purpose of , Destroyed API The stability of , It also makes programmers lose choice and fun . such as ,Py3.9 by str Object added removeprefix() and removesuffix() Two methods , Used to delete the prefix and suffix of the string respectively .
>>> s = '[ The host ] Go to Hong Kong to get a free kick in the front court (1:1)'
>>> s.removeprefix('[ The host ]')
' Go to Hong Kong to get a free kick in the front court (1:1)'
>>> s.removesuffix('(1:1)')
'[ The host ] Go to Hong Kong to get a free kick in the front court '
There are many requirements for similar applications , If you want to join in str Object's method library ,str The object will be huge . The writing of this kind of function , It should be left to the programmer ,Python The language project team only needs to focus on the basic and core approach . actually , These two methods are implemented , It's just a line of code .
>>> s = '[ The host ] Go to Hong Kong to get a free kick in the front court (1:1)'
>>> s if s.find('[ The host ]') < 0 else s[len('[ The host ]'):]
' Go to Hong Kong to get a free kick in the front court (1:1)'
>>> s if (n:=s.rfind('(1:1)')) < 0 else s[:n]
'[ The host ] Go to Hong Kong to get a free kick in the front court '
Py2 Time ,u Is the most common string prefix ,Py3 Time ,u The prefix disappeared ,b Became the most common string prefix . Whether it's Py2 still Py3, Native string prefix r All are Python Familiar customers in the eyes of programmers . from Py3.6 Start , Suddenly, a new string prefix appears .
>>> score = '1:1'
>>> f' The current score {score}'
' The current score 1:1'
Previous prefix , It's just a logo , current f The prefix becomes an operator , The world of reason, which feels wonderful, suddenly collapses ! However , This is just the beginning , Worse things happen in Py3.8 On the version , They're doing this again f The prefix adds an equal sign (=) Support for .
>>> Chinese language and literature =95
>>> mathematics =100
>>> f'{ Chinese language and literature =},{ mathematics =}'
' Chinese language and literature =95, mathematics =100'
MyGod, Where is the code , It's a magic charm ! Tell the truth , When formatting a string , except C stylistic % Outside , I don't even format() Functions have never been used , Now it is possible to face the enhanced version written by colleagues f Prefix code . Sad me , I can only laugh it off .
Py3.6 When it was released , There are legends everywhere , The dictionary is in order . At first, I thought it was just we media for novelty , Just talk about , Eye catching . Logically , A dictionary is an unordered set of data , Relying only on key retrieval , If the dictionary is in order , It's not a dictionary . little does one think ,Py3.7 Actually will “ The dictionary keeps the insertion order ” Officially announced as a new feature . fortunately , What the authorities say is “ The dictionary keeps the insertion order ”, instead of “ The dictionary is in order ”, Finally, the last pants are reserved for logic .
I say the dictionary is out of order , It's not that dictionaries are really out of order when they're implemented on physical entities , It means that the order is not clearly defined for users , Cannot be used as a feature of data . Maybe Py3.7 A new mechanism is used to store and retrieve dictionary data more efficiently , But that's not what programmers care about . The new mechanism brings stable dictionary order , It's not a dictionary property that we can trust and use .
When it comes to the definition of functions and the transfer of parameters , I'm afraid there's nothing like Python More flexible language . Convenient at the same time , Positional arguments 、 Default parameters 、 Variable parameters 、 Keyword parameters and other parameter types and use order , It also brings a lot of confusion to programmers . However ,Py3.8 Firmly believe that , The use of function parameters is not confusing enough , It needs a little more stimulation , In order to achieve the goal from chaos to governance . therefore , Function parameter qualifier on stage —— To enhance the effect ,Python The official choice is slash (/) As a representation of this qualifier .
Let's try to read the following code .
>>> def func(a, b, /, c, d, *, e, f):
print('OK')
>>> func(1,2,3,4,e=5,f=6)
OK
>>> func(1,2,3,d=4,e=5,f=6)
OK
here ,a, b It's a position parameter ,e, f It's a keyword parameter ,c, d It can be either a parameter or a parameter , It can also be a keyword parameter . Okay , So much about function parameter qualifiers , There's no need to —— Unless you're using Python Function completely simulates C Functions written in code .
When it comes to generics ,Python Programmers usually have two expressions : One is surprise :“Python Do you have generics ?”; The other is smiling :“Python Is there a pattern ?” Let's not talk about Python whether “ There are types ”, As a dynamic language , Isn't generics inborn ? Maybe Python The team doesn't think so , Or they think Python Programmers don't think so . In order to be worthy of the rank of the big guy in the programming language rankings , from Py3.4 Start ,Python The team is for Python A custom function decorator . But this mechanism is too far fetched , Use it to write a lot of ugly code , Not many people will use it .
>>> from functools import singledispatch
>>> @singledispatch
def say_hello(x):
print(' I'm sorry , i don't know you ')
>>> @say_hello.register(int)
def _(x):
print(' Hello , Integers ')
>>> @say_hello.register(str)
def _(x):
print(' Hello , character string ')
>>> say_hello(5)
Hello , Integers
>>> say_hello('abc')
Hello , character string
>>> say_hello([1,2,3])
I'm sorry , i don't know you
There's a lot of code above , It just defines a function say_hello(), You can react differently depending on the type of input parameter . If you don't use generic decorators , It's easier to implement and easier to read .
>>> def say_hello(x):
if isinstance(x, int):
print(' Hello , Integers ')
elif isinstance(x, str):
print(' Hello , character string ')
else:
print(' I'm sorry , i don't know you ')
>>> say_hello(5)
Hello , Integers
>>> say_hello('abc')
Hello , character string
>>> say_hello([1,2,3])
I'm sorry , i don't know you
When I first read about typing.List and typing.Dict When , For a while , It feels like reading java Or is it C++ Code for . Why not familiar list and dict Well ? Just for type cues (type hints) , In order to make the integrated development tools understand the code , Sheng Sheng has made a comparison with list and dict And complicated concepts . The end result is ,IDE Read the code , Programmers don't understand .
Fortunately Py3.9 Improved the type prompt , Support for generics in type hints is provided for both built-in and standard library collection types , Solved all the time Python There are two kinds of code list(list and typing.List) Type of embarrassing situation , It's a mending act after a sheep has been lost .
I have written so much about it , I hope it won't let Python Programmers are frustrated . in fact , No matter how I make complaints about it ,Python Still a great programming language . The point of this paper is , It's just my personal view as a fundamentalist , A little bit of fun . Welcome to express your opinions , Don't care about my face . I'll pretend I can't see , No explanation, no debate . Please make a detour .