~sschwarzer/ftputil#74: 
Implement `StatResult` as a named tuple

Currently StatResult inherits from tuple. However, as ftputil 3.0 and above require at least Python 2.6, we can safely assume that collections.namedtuple is available, so we can use this to simplify the implementation a bit.

Check if the module name or class name are different in Python 3.

Status
RESOLVED INVALID
Submitter
schwa (unverified)
Assigned to
No-one
Submitted
10 years ago
Updated
10 years ago
Labels
library

schwa (unverified) 9 years ago · edit

namedtuple doesn't work well for StatResult which should have some default attribute values.

In [1]: import collections

In [2]: Result = collections.namedtuple("Result", ["a", "b", "c"])

In [3]: class MyResult(Result):
   ...:     
   ...:     def __init__(self):
   ...:         # Actually can't be modified because tuples are immutable.
   ...:         self.c = 3
   ...:         

In [4]: mr = MyResult(1, 2)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-4-e68f8d253c6e> in <module>()
----> 1 mr = MyResult(1, 2)

TypeError: __new__() takes exactly 4 arguments (3 given)

In [5]: mr = MyResult(1, 2, 3)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-5-f0ac3da19b2e> in <module>()
----> 1 mr = MyResult(1, 2, 3)

TypeError: __init__() takes exactly 1 argument (4 given)

I guess I could make namedtuple work by creating a derived class overriding __new__, but then it gets more complicated than the current approach.

Register here or Log in to comment, or comment via email.