In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-21 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly introduces "how to use the missing () function in Python". In daily operation, I believe many people have doubts about how to use the missing () function in Python. The editor consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful to answer the doubts about "how to use the missing () function in Python". Next, please follow the editor to study!
The main concerns of this paper are as follows:
(1) who on earth is missing ()?
(2) what is special about missing ()? Good at "changing the living" magic?
(3) is missing () really an exception to the above findings? If so, why is there such a special case?
1. Some valuable missing ()
When taking values from ordinary dictionaries, there may be situations where key does not exist:
Dd = {'name':'PythonCat'} dd.get (' age') # result: Nonedd.get ('age', 18) # result: 18dd [' age'] # error KeyErrordd.__getitem__ ('age') # equals dd [' age']
For the get () method, it has a return value, and a second parameter can be passed in as a return if key does not exist, so it is acceptable. However, the other two ways of writing will report errors.
In order to solve the problem of the latter two ways of writing, the missing () magic method can be used.
Now, suppose we have a request to take the value for a key from the dictionary, return a value if there is a value, insert a key if there is no value, and give it a default value (such as an empty list).
If you use native dict, it's not easy to implement, but Python provides a very useful extension class collections.defaultdict:
As shown in the figure, when fetching a key that does not exist, the KeyError is no longer reported, but is stored in the dictionary by default.
Why can defaultdict do this?
The reason is that defaultdict also defines a missing () method after inheriting the built-in type dict. When getitem takes a value that does not exist, it calls the factory function passed in the input parameter (the example above is to call list () to create an empty list).
As the most typical example, defaultdict wrote in the documentation comments:
In short, the main purpose of missing () is to be called by getitem when key is missing, thus avoiding KeyError.
Another typical usage example is collections.Counter, which is also a subclass of dict. When taking the key that is not counted, the return count is 0:
2. Haunted missing ()
As you can see from the above, missing () is called when getitem () cannot get a value, but I inadvertently found a detail: when getitem () does not get a value, it does not necessarily call missing ().
This is because it is not a necessary attribute of the built-in type and is not predefined in the dictionary base class.
If you take the property value directly from the dict type, it will report that the property does not exist: AttributeError: type object' object' has no attribute'_ _ missing__'.
Looking at it using dir (), it is found that the attribute does not exist:
If you look at it from the parent class of dict, object, you will find the same result.
What's going on? Why is there no missing attribute in both dict and object?
However, looking at the latest official documentation, this attribute is clearly included in object:
Source: 3. Data model-Python 3.10.1 documentationmissing#object.missing
That is, in theory, missing is predefined in the object class, as its documentation proves, but in practice it is not defined! There is a deviation between the document and reality!
In this way, when subclasses of dict (such as defaultdict and Counter) define missing, the magic method actually belongs only to that subclass, that is, it is a magic method born in the subclass!
Accordingly, I have an immature guess: getitem () will determine whether the current object is a subclass of dict and has missing () before calling it. (if there is a method in the parent class, it will not be judged first, but will be called directly).
I expressed this conjecture in the exchange group, and some students quickly found verification in the CPython source code:
And this is interesting, the magic method that exists on the subclass of the built-in type, throughout the whole Python world, I am afraid it is difficult to find a second example.
I suddenly have an association: this haunted missing () is like a magician who is good at playing "big change", first let the audience see him through the glass (that is, official documents), but when he opens the door, he is not inside (that is, the built-in type), and then change the props, he appears intact (that is, a subclass of dict).
3. Enchanted missing ()
The magic of missing (), in addition to its own "magic", it also needs a powerful "magic" to drive.
I found that the native magic methods are independent of each other, and they may have the same core logic in the C language interface, but there is no invocation relationship in the Python language interface:
This "old age and death" performance of the magic method violates the general principle of code reuse and is the reason for some strange behavior of built-in subclasses.
The official Python would rather provide new UserString, UserList, and UserDict subclasses than reuse magic methods. The only reasonable explanation seems to be that it is too expensive for magic methods to call each other.
However, for the special case missing (), Python has to compromise and have to pay this price!
Missing () is the "second-class citizen" of the magic method. It has no independent invocation entry and can only be called passively by getitem (), that is, missing () depends on getitem ().
Unlike those "first-class citizens", such as init (), enter (), len (), eq (), and so on, they are either triggered at a node in the object life cycle or execution process, or triggered by a built-in function or operator, which are relatively independent events and have nothing to rely on.
Missing () relies on getitem () to implement method calls, while getitem () also relies on missing () to achieve full functionality.
To achieve this, getitem () opens a back door in the interpreter code and returns to the Python interface from the C interface to call that specific method called "missing".
And this is the real "magic", so far, missing () seems to be the only magic way to enjoy such treatment!
At this point, the study on "how to use the missing () function in Python" 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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.