Changeset 1625:c84dd64b3eea


Ignore:
Timestamp:
Dec 23, 2015, 8:18:45 PM (5 years ago)
Author:
Stefan Schwarzer <sschwarzer@…>
Branch:
default
Message:
Add `__repr__` so that a `StatResult` looks like a named tuple (#91)

Contrary to the suggestion in ticket #91, I can't turn `StatResult`
into a `namedtuple`. Since `StatResult` inherits from `tuple`, its
constructor takes a tuple of the n items to use:

  StatResult((item1, item2, ...))

On the other hand, the constructor of a `namedtuple` takes n arguments
for the tuple items, so the API would become

  StatResult(item1, item2, ...)

Since `StatResult` is a public API for implementation of custom parsers,
I can't just change it.

However, since the main idea behind using a `namedtuple` is its
representation, I added a `__repr__` method so that the representation
of a `StatResult` looks like the representation of a `namedtuple`.

Note that the `__repr__` result is different under Python 2 and 3. The
strings in the `StatResult` are always unicode strings and those have
a `u` prefix under Python 2. I had considered removing the prefix for
Python 2, but I think this could be very confusing during debugging
(including for me).
Files:
2 edited

Legend:

Unmodified
Added
Removed
  • ftputil/stat.py

    r1586 r1625  
    1 # Copyright (C) 2002-2014, Stefan Schwarzer <sschwarzer@sschwarzer.net>
     1# Copyright (C) 2002-2015, Stefan Schwarzer <sschwarzer@sschwarzer.net>
    22# and ftputil contributors (see `doc/contributors.txt`)
    33# See the file LICENSE for licensing terms.
     
    6363            raise AttributeError("'StatResult' object has no attribute '{0}'".
    6464                                 format(attr_name))
     65
     66    def __repr__(self):
     67        # "Invert" `_index_mapping` so that we can look up the names
     68        # for the tuple indices.
     69        index_to_name = dict((v, k) for k, v in self._index_mapping.items())
     70        argument_strings = []
     71        for index, item in enumerate(self):
     72            argument_strings.append("{0}={1!r}".format(index_to_name[index],
     73                                                       item))
     74        return "{0}({1})".format(type(self).__name__,
     75                                 ", ".join(argument_strings))
     76
    6577
    6678#
  • test/test_stat.py

    r1579 r1625  
    1 # Copyright (C) 2003-2014, Stefan Schwarzer <sschwarzer@sschwarzer.net>
     1# Copyright (C) 2003-2015, Stefan Schwarzer <sschwarzer@sschwarzer.net>
    22# and ftputil contributors (see `doc/contributors.txt`)
    33# See the file LICENSE for licensing terms.
     
    1212
    1313import ftputil
     14import ftputil.compat
    1415import ftputil.error
    1516import ftputil.stat
     
    366367          _test_stat(session_factory=mock_ftplib.MockUnixFormatSession)
    367368
     369    def test_repr(self):
     370        """Test if the `repr` result looks like a named tuple."""
     371        stat_result = self.stat._lstat("/home/sschwarzer/index.html")
     372        # Only under Python 2, unicode strings have the `u` prefix.
     373        if ftputil.compat.python_version == 2:
     374            expected_result = (
     375              "StatResult(st_mode=33188, st_ino=None, st_dev=None, "
     376              "st_nlink=1, st_uid=u'45854', st_gid=u'200', st_size=4604, "
     377              "st_atime=None, st_mtime=1421705460.0, st_ctime=None)")
     378        else:
     379            expected_result = (
     380              "StatResult(st_mode=33188, st_ino=None, st_dev=None, "
     381              "st_nlink=1, st_uid='45854', st_gid='200', st_size=4604, "
     382              "st_atime=None, st_mtime=1421705460.0, st_ctime=None)")
     383        self.assertEqual(repr(stat_result), expected_result)
     384
    368385    def test_failing_lstat(self):
    369386        """Test whether `lstat` fails for a nonexistent path."""
Note: See TracChangeset for help on using the changeset viewer.