The dangerous shift: Python is moving from simplicity to bloat, from utility to kitsch

Tianyuan prodigal son 2020-11-13 09:06:09
dangerous shift python moving simplicity


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 .

1. Static type checking for kitsch

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 .

2. The variable type declaration that adds to the story

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 !

3. Type annotation of functions and parameters like chicken ribs

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 .

4. Unlimited extension operators

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}

5. The string method of unauthorized substitution

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 '

6. A string prefix that's ridiculous

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 .

7. Illogical dictionary order

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 .

8. Function parameter qualifiers for fear of chaos

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 .

9. Generic functions with no sense of elegance

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

10. Make up for the lost sheep in the face

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 .

版权声明
本文为[Tianyuan prodigal son]所创,转载请带上原文链接,感谢

  1. 利用Python爬虫获取招聘网站职位信息
  2. Using Python crawler to obtain job information of recruitment website
  3. Several highly rated Python libraries arrow, jsonpath, psutil and tenacity are recommended
  4. Python装饰器
  5. Python实现LDAP认证
  6. Python decorator
  7. Implementing LDAP authentication with Python
  8. Vscode configures Python development environment!
  9. In Python, how dare you say you can't log module? ️
  10. 我收藏的有关Python的电子书和资料
  11. python 中 lambda的一些tips
  12. python中字典的一些tips
  13. python 用生成器生成斐波那契数列
  14. python脚本转pyc踩了个坑。。。
  15. My collection of e-books and materials about Python
  16. Some tips of lambda in Python
  17. Some tips of dictionary in Python
  18. Using Python generator to generate Fibonacci sequence
  19. The conversion of Python script to PyC stepped on a pit...
  20. Python游戏开发,pygame模块,Python实现扫雷小游戏
  21. Python game development, pyGame module, python implementation of minesweeping games
  22. Python实用工具,email模块,Python实现邮件远程控制自己电脑
  23. Python utility, email module, python realizes mail remote control of its own computer
  24. 毫无头绪的自学Python,你可能连门槛都摸不到!【最佳学习路线】
  25. Python读取二进制文件代码方法解析
  26. Python字典的实现原理
  27. Without a clue, you may not even touch the threshold【 Best learning route]
  28. Parsing method of Python reading binary file code
  29. Implementation principle of Python dictionary
  30. You must know the function of pandas to parse JSON data - JSON_ normalize()
  31. Python实用案例,私人定制,Python自动化生成爱豆专属2021日历
  32. Python practical case, private customization, python automatic generation of Adu exclusive 2021 calendar
  33. 《Python实例》震惊了,用Python这么简单实现了聊天系统的脏话,广告检测
  34. "Python instance" was shocked and realized the dirty words and advertisement detection of the chat system in Python
  35. Convolutional neural network processing sequence for Python deep learning
  36. Python data structure and algorithm (1) -- enum type enum
  37. 超全大厂算法岗百问百答(推荐系统/机器学习/深度学习/C++/Spark/python)
  38. 【Python进阶】你真的明白NumPy中的ndarray吗?
  39. All questions and answers for algorithm posts of super large factories (recommended system / machine learning / deep learning / C + + / spark / Python)
  40. [advanced Python] do you really understand ndarray in numpy?
  41. 【Python进阶】Python进阶专栏栏主自述:不忘初心,砥砺前行
  42. [advanced Python] Python advanced column main readme: never forget the original intention and forge ahead
  43. python垃圾回收和缓存管理
  44. java调用Python程序
  45. java调用Python程序
  46. Python常用函数有哪些?Python基础入门课程
  47. Python garbage collection and cache management
  48. Java calling Python program
  49. Java calling Python program
  50. What functions are commonly used in Python? Introduction to Python Basics
  51. Python basic knowledge
  52. Anaconda5.2 安装 Python 库(MySQLdb)的方法
  53. Python实现对脑电数据情绪分析
  54. Anaconda 5.2 method of installing Python Library (mysqldb)
  55. Python implements emotion analysis of EEG data
  56. Master some advanced usage of Python in 30 seconds, which makes others envy it
  57. python爬取百度图片并对图片做一系列处理
  58. Python crawls Baidu pictures and does a series of processing on them
  59. python链接mysql数据库
  60. Python link MySQL database