Is there any use for _tuple in Python?

I read the official collections.namedtuple documentation today and found _tuple in the __new__ method. I did not find where _tuple was defined.

You can try to run the code below in Python, it does not cause any errors.

 >>> Point = namedtuple('Point', ['x', 'y'], verbose=True) class Point(tuple): 'Point(x, y)' __slots__ = () _fields = ('x', 'y') def __new__(_cls, x, y): 'Create a new instance of Point(x, y)' return _tuple.__new__(_cls, (x, y)) # Here. Why _tuple? 

Update: What are the benefits

 from builtins import property as _property, tuple as _tuple 

Is it just that tuple be protected value? I'm right?

+5
source share
1 answer

From the general source code (you can see the source code generated for this particular namedtuple by printing Point._source ):

 from builtins import property as _property, tuple as _tuple 

So _tuple here is just an alias for the built-in type tuple :

 In [1]: from builtins import tuple as _tuple In [2]: tuple is _tuple Out[2]: True 

collections.namedtuple was added in Python 2.6.0. This was the source code for the __new__ method:

 def __new__(cls, %(argtxt)s): return tuple.__new__(cls, (%(argtxt)s)) \n 

The fact is that the source code is in a line. They later format it using % locals() . If tuple was specified in argtxt , then tuple.__new__ would call the __new__ method of any tuple field. In contrast, _tuple works as expected because namedtuple does not allow field names starting with _ .

Fixed a bug in the release of Python 2.6.3 (see changelog - collections.namedtuple () did not work with the following field names: cls, self, tuple, itemgetter and property).

+8
source

Source: https://habr.com/ru/post/1200463/


All Articles