[issue5336] collections.namedtuple generates code causing PyChecker warnings

Mikhail Bessonov report at bugs.python.org
Sat Feb 21 10:24:53 CET 2009


New submission from Mikhail Bessonov <zahoo at mail.ru>:

The first argument of some methods generated by collections.namedtuple 
differs from 'self'. It upsets a number of code checkers, notably 
PyChecker, because in most cases it is indeed an error. As a result, 
the code using collections.namedtuple does not pass PyChecker, which is 
a commit or release requirement in many projects.

The solution would be to rename the first argument of each method to 
'self'.

A sample 2-line program demonstrating the error is provided below.

import collections
DocRecord = collections.namedtuple('DocRecord', 'id, date, name, desc',
		verbose = True)

Here's the PyChecker output. Methods that cause trouble are 'def _asdict
(t):', etc.

E:\src\mini-crawler>E:\Python26\python.exe E:\Python26\Lib\site-packages
\pychecker\checker.py test.py 
class DocRecord(tuple):
        'DocRecord(id, date, name, desc)' 

        __slots__ = () 

        _fields = ('id', 'date', 'name', 'desc') 

        def __new__(cls, id, date, name, desc):
            return tuple.__new__(cls, (id, date, name, desc)) 

        @classmethod
        def _make(cls, iterable, new=tuple.__new__, len=len):
            'Make a new DocRecord object from a sequence or iterable'
            result = new(cls, iterable)
            if len(result) != 4:
                raise TypeError('Expected 4 arguments, got %d' % len
(result))
            return result 

        def __repr__(self):
            return 'DocRecord(id=%r, date=%r, name=%r, desc=%r)' % self 

        def _asdict(t):
            'Return a new dict which maps field names to their values'
            return {'id': t[0], 'date': t[1], 'name': t[2], 'desc': t
[3]} 

        def _replace(self, **kwds):
            'Return a new DocRecord object replacing specified fields 
with new values'
            result = self._make(map(kwds.pop, ('id', 'date', 'name', 
'desc'), self))
            if kwds:
                raise ValueError('Got unexpected field names: %r' % 
kwds.keys())
            return result 

        def __getnewargs__(self):
            return tuple(self) 

        id = property(itemgetter(0))
        date = property(itemgetter(1))
        name = property(itemgetter(2))
        desc = property(itemgetter(3))


Warnings...

<string>:22: self is not first method argument

----------
components: Library (Lib)
messages: 82562
nosy: mbessonov
severity: normal
status: open
title: collections.namedtuple generates code causing PyChecker warnings
type: behavior
versions: Python 2.6

_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue5336>
_______________________________________


More information about the Python-bugs-list mailing list