[Python-checkins] cpython: Issue #22033: Reprs of most Python implemened classes now contain actual

serhiy.storchaka python-checkins at python.org
Fri Jul 25 22:36:17 CEST 2014


http://hg.python.org/cpython/rev/42276ad3acef
changeset:   91870:42276ad3acef
user:        Serhiy Storchaka <storchaka at gmail.com>
date:        Fri Jul 25 23:36:00 2014 +0300
summary:
  Issue #22033: Reprs of most Python implemened classes now contain actual
class name instead of hardcoded one.

files:
  Lib/_pyio.py                          |  10 +-
  Lib/concurrent/futures/_base.py       |  15 ++-
  Lib/datetime.py                       |  49 ++++++++------
  Lib/doctest.py                        |   5 +-
  Lib/email/headerregistry.py           |   6 +-
  Lib/fractions.py                      |   3 +-
  Lib/http/client.py                    |   3 +-
  Lib/http/cookiejar.py                 |   2 +-
  Lib/idlelib/WidgetRedirector.py       |   8 +-
  Lib/multiprocessing/dummy/__init__.py |   2 +-
  Lib/multiprocessing/managers.py       |  10 +-
  Lib/multiprocessing/pool.py           |   2 +-
  Lib/multiprocessing/synchronize.py    |  12 +-
  Lib/multiprocessing/util.py           |   7 +-
  Lib/pydoc.py                          |   3 +-
  Lib/subprocess.py                     |   2 +-
  Lib/urllib/parse.py                   |   2 +-
  Lib/uuid.py                           |   2 +-
  Lib/weakref.py                        |   4 +-
  Lib/wsgiref/headers.py                |   2 +-
  Lib/xml/dom/minidom.py                |   5 +-
  Lib/xml/etree/ElementTree.py          |   4 +-
  Lib/xmlrpc/client.py                  |  15 ++--
  Misc/NEWS                             |   3 +
  24 files changed, 102 insertions(+), 74 deletions(-)


diff --git a/Lib/_pyio.py b/Lib/_pyio.py
--- a/Lib/_pyio.py
+++ b/Lib/_pyio.py
@@ -808,13 +808,14 @@
                         .format(self.__class__.__name__))
 
     def __repr__(self):
-        clsname = self.__class__.__name__
+        modname = self.__class__.__module__
+        clsname = self.__class__.__qualname__
         try:
             name = self.name
         except AttributeError:
-            return "<_pyio.{0}>".format(clsname)
+            return "<{}.{}>".format(modname, clsname)
         else:
-            return "<_pyio.{0} name={1!r}>".format(clsname, name)
+            return "<{}.{} name={!r}>".format(modname, clsname, name)
 
     ### Lower-level APIs ###
 
@@ -1635,7 +1636,8 @@
     #   - "chars_..." for integer variables that count decoded characters
 
     def __repr__(self):
-        result = "<_pyio.TextIOWrapper"
+        result = "<{}.{}".format(self.__class__.__module__,
+                                 self.__class__.__qualname__)
         try:
             name = self.name
         except AttributeError:
diff --git a/Lib/concurrent/futures/_base.py b/Lib/concurrent/futures/_base.py
--- a/Lib/concurrent/futures/_base.py
+++ b/Lib/concurrent/futures/_base.py
@@ -302,17 +302,20 @@
         with self._condition:
             if self._state == FINISHED:
                 if self._exception:
-                    return '<Future at %s state=%s raised %s>' % (
-                        hex(id(self)),
+                    return '<%s at %#x state=%s raised %s>' % (
+                        self.__class__.__name__,
+                        id(self),
                         _STATE_TO_DESCRIPTION_MAP[self._state],
                         self._exception.__class__.__name__)
                 else:
-                    return '<Future at %s state=%s returned %s>' % (
-                        hex(id(self)),
+                    return '<%s at %#x state=%s returned %s>' % (
+                        self.__class__.__name__,
+                        id(self),
                         _STATE_TO_DESCRIPTION_MAP[self._state],
                         self._result.__class__.__name__)
-            return '<Future at %s state=%s>' % (
-                    hex(id(self)),
+            return '<%s at %#x state=%s>' % (
+                    self.__class__.__name__,
+                    id(self),
                    _STATE_TO_DESCRIPTION_MAP[self._state])
 
     def cancel(self):
diff --git a/Lib/datetime.py b/Lib/datetime.py
--- a/Lib/datetime.py
+++ b/Lib/datetime.py
@@ -414,15 +414,19 @@
 
     def __repr__(self):
         if self._microseconds:
-            return "%s(%d, %d, %d)" % ('datetime.' + self.__class__.__name__,
-                                       self._days,
-                                       self._seconds,
-                                       self._microseconds)
+            return "%s.%s(%d, %d, %d)" % (self.__class__.__module__,
+                                          self.__class__.__qualname__,
+                                          self._days,
+                                          self._seconds,
+                                          self._microseconds)
         if self._seconds:
-            return "%s(%d, %d)" % ('datetime.' + self.__class__.__name__,
-                                   self._days,
-                                   self._seconds)
-        return "%s(%d)" % ('datetime.' + self.__class__.__name__, self._days)
+            return "%s.%s(%d, %d)" % (self.__class__.__module__,
+                                      self.__class__.__qualname__,
+                                      self._days,
+                                      self._seconds)
+        return "%s.%s(%d)" % (self.__class__.__module__,
+                              self.__class__.__qualname__,
+                              self._days)
 
     def __str__(self):
         mm, ss = divmod(self._seconds, 60)
@@ -700,10 +704,11 @@
         >>> repr(dt)
         'datetime.datetime(2010, 1, 1, 0, 0, tzinfo=datetime.timezone.utc)'
         """
-        return "%s(%d, %d, %d)" % ('datetime.' + self.__class__.__name__,
-                                   self._year,
-                                   self._month,
-                                   self._day)
+        return "%s.%s(%d, %d, %d)" % (self.__class__.__module__,
+                                      self.__class__.__qualname__,
+                                      self._year,
+                                      self._month,
+                                      self._day)
     # XXX These shouldn't depend on time.localtime(), because that
     # clips the usable dates to [1970 .. 2038).  At least ctime() is
     # easily done without using strftime() -- that's better too because
@@ -1155,8 +1160,9 @@
             s = ", %d" % self._second
         else:
             s = ""
-        s= "%s(%d, %d%s)" % ('datetime.' + self.__class__.__name__,
-                             self._hour, self._minute, s)
+        s= "%s.%s(%d, %d%s)" % (self.__class__.__module__,
+                                self.__class__.__qualname__,
+                                self._hour, self._minute, s)
         if self._tzinfo is not None:
             assert s[-1:] == ")"
             s = s[:-1] + ", tzinfo=%r" % self._tzinfo + ")"
@@ -1569,8 +1575,9 @@
             del L[-1]
         if L[-1] == 0:
             del L[-1]
-        s = ", ".join(map(str, L))
-        s = "%s(%s)" % ('datetime.' + self.__class__.__name__, s)
+        s = "%s.%s(%s)" % (self.__class__.__module__,
+                           self.__class__.__qualname__,
+                           ", ".join(map(str, L)))
         if self._tzinfo is not None:
             assert s[-1:] == ")"
             s = s[:-1] + ", tzinfo=%r" % self._tzinfo + ")"
@@ -1857,10 +1864,12 @@
         if self is self.utc:
             return 'datetime.timezone.utc'
         if self._name is None:
-            return "%s(%r)" % ('datetime.' + self.__class__.__name__,
-                               self._offset)
-        return "%s(%r, %r)" % ('datetime.' + self.__class__.__name__,
-                               self._offset, self._name)
+            return "%s.%s(%r)" % (self.__class__.__module__,
+                                  self.__class__.__qualname__,
+                                  self._offset)
+        return "%s.%s(%r, %r)" % (self.__class__.__module__,
+                                  self.__class__.__qualname__,
+                                  self._offset, self._name)
 
     def __str__(self):
         return self.tzname(None)
diff --git a/Lib/doctest.py b/Lib/doctest.py
--- a/Lib/doctest.py
+++ b/Lib/doctest.py
@@ -533,8 +533,9 @@
             examples = '1 example'
         else:
             examples = '%d examples' % len(self.examples)
-        return ('<DocTest %s from %s:%s (%s)>' %
-                (self.name, self.filename, self.lineno, examples))
+        return ('<%s %s from %s:%s (%s)>' %
+                (self.__class__.__name__,
+                 self.name, self.filename, self.lineno, examples))
 
     def __eq__(self, other):
         if type(self) is not type(other):
diff --git a/Lib/email/headerregistry.py b/Lib/email/headerregistry.py
--- a/Lib/email/headerregistry.py
+++ b/Lib/email/headerregistry.py
@@ -80,7 +80,8 @@
         return lp
 
     def __repr__(self):
-        return "Address(display_name={!r}, username={!r}, domain={!r})".format(
+        return "{}(display_name={!r}, username={!r}, domain={!r})".format(
+                        self.__class__.__name__,
                         self.display_name, self.username, self.domain)
 
     def __str__(self):
@@ -131,7 +132,8 @@
         return self._addresses
 
     def __repr__(self):
-        return "Group(display_name={!r}, addresses={!r}".format(
+        return "{}(display_name={!r}, addresses={!r}".format(
+                 self.__class__.__name__,
                  self.display_name, self.addresses)
 
     def __str__(self):
diff --git a/Lib/fractions.py b/Lib/fractions.py
--- a/Lib/fractions.py
+++ b/Lib/fractions.py
@@ -280,7 +280,8 @@
 
     def __repr__(self):
         """repr(self)"""
-        return ('Fraction(%s, %s)' % (self._numerator, self._denominator))
+        return '%s(%s, %s)' % (self.__class__.__name__,
+                               self._numerator, self._denominator)
 
     def __str__(self):
         """str(self)"""
diff --git a/Lib/http/client.py b/Lib/http/client.py
--- a/Lib/http/client.py
+++ b/Lib/http/client.py
@@ -1334,7 +1334,8 @@
             e = ', %i more expected' % self.expected
         else:
             e = ''
-        return 'IncompleteRead(%i bytes read%s)' % (len(self.partial), e)
+        return '%s(%i bytes read%s)' % (self.__class__.__name__,
+                                        len(self.partial), e)
     def __str__(self):
         return repr(self)
 
diff --git a/Lib/http/cookiejar.py b/Lib/http/cookiejar.py
--- a/Lib/http/cookiejar.py
+++ b/Lib/http/cookiejar.py
@@ -805,7 +805,7 @@
             args.append("%s=%s" % (name, repr(attr)))
         args.append("rest=%s" % repr(self._rest))
         args.append("rfc2109=%s" % repr(self.rfc2109))
-        return "Cookie(%s)" % ", ".join(args)
+        return "%s(%s)" % (self.__class__.__name__, ", ".join(args))
 
 
 class CookiePolicy:
diff --git a/Lib/idlelib/WidgetRedirector.py b/Lib/idlelib/WidgetRedirector.py
--- a/Lib/idlelib/WidgetRedirector.py
+++ b/Lib/idlelib/WidgetRedirector.py
@@ -47,8 +47,9 @@
         tk.createcommand(w, self.dispatch)
 
     def __repr__(self):
-        return "WidgetRedirector(%s<%s>)" % (self.widget.__class__.__name__,
-                                             self.widget._w)
+        return "%s(%s<%s>)" % (self.__class__.__name__,
+                               self.widget.__class__.__name__,
+                               self.widget._w)
 
     def close(self):
         "Unregister operations and revert redirection created by .__init__."
@@ -142,7 +143,8 @@
         self.orig_and_operation = (redir.orig, operation)
 
     def __repr__(self):
-        return "OriginalCommand(%r, %r)" % (self.redir, self.operation)
+        return "%s(%r, %r)" % (self.__class__.__name__,
+                               self.redir, self.operation)
 
     def __call__(self, *args):
         return self.tk_call(self.orig_and_operation + args)
diff --git a/Lib/multiprocessing/dummy/__init__.py b/Lib/multiprocessing/dummy/__init__.py
--- a/Lib/multiprocessing/dummy/__init__.py
+++ b/Lib/multiprocessing/dummy/__init__.py
@@ -86,7 +86,7 @@
             if not name.startswith('_'):
                 temp.append('%s=%r' % (name, value))
         temp.sort()
-        return 'Namespace(%s)' % str.join(', ', temp)
+        return '%s(%s)' % (self.__class__.__name__, ', '.join(temp))
 
 dict = dict
 list = list
diff --git a/Lib/multiprocessing/managers.py b/Lib/multiprocessing/managers.py
--- a/Lib/multiprocessing/managers.py
+++ b/Lib/multiprocessing/managers.py
@@ -65,8 +65,8 @@
         (self.typeid, self.address, self.id) = state
 
     def __repr__(self):
-        return 'Token(typeid=%r, address=%r, id=%r)' % \
-               (self.typeid, self.address, self.id)
+        return '%s(typeid=%r, address=%r, id=%r)' % \
+               (self.__class__.__name__, self.typeid, self.address, self.id)
 
 #
 # Function for communication with a manager's server process
@@ -803,8 +803,8 @@
         return self._getvalue()
 
     def __repr__(self):
-        return '<%s object, typeid %r at %s>' % \
-               (type(self).__name__, self._token.typeid, '0x%x' % id(self))
+        return '<%s object, typeid %r at %#x>' % \
+               (type(self).__name__, self._token.typeid, id(self))
 
     def __str__(self):
         '''
@@ -901,7 +901,7 @@
             if not name.startswith('_'):
                 temp.append('%s=%r' % (name, value))
         temp.sort()
-        return 'Namespace(%s)' % str.join(', ', temp)
+        return '%s(%s)' % (self.__class__.__name__, ', '.join(temp))
 
 class Value(object):
     def __init__(self, typecode, value, lock=True):
diff --git a/Lib/multiprocessing/pool.py b/Lib/multiprocessing/pool.py
--- a/Lib/multiprocessing/pool.py
+++ b/Lib/multiprocessing/pool.py
@@ -87,7 +87,7 @@
                                                              self.exc)
 
     def __repr__(self):
-        return "<MaybeEncodingError: %s>" % str(self)
+        return "<%s: %s>" % (self.__class__.__name__, self)
 
 
 def worker(inqueue, outqueue, initializer=None, initargs=(), maxtasks=None,
diff --git a/Lib/multiprocessing/synchronize.py b/Lib/multiprocessing/synchronize.py
--- a/Lib/multiprocessing/synchronize.py
+++ b/Lib/multiprocessing/synchronize.py
@@ -134,7 +134,7 @@
             value = self._semlock._get_value()
         except Exception:
             value = 'unknown'
-        return '<Semaphore(value=%s)>' % value
+        return '<%s(value=%s)>' % (self.__class__.__name__, value)
 
 #
 # Bounded semaphore
@@ -150,8 +150,8 @@
             value = self._semlock._get_value()
         except Exception:
             value = 'unknown'
-        return '<BoundedSemaphore(value=%s, maxvalue=%s)>' % \
-               (value, self._semlock.maxvalue)
+        return '<%s(value=%s, maxvalue=%s)>' % \
+               (self.__class__.__name__, value, self._semlock.maxvalue)
 
 #
 # Non-recursive lock
@@ -176,7 +176,7 @@
                 name = 'SomeOtherProcess'
         except Exception:
             name = 'unknown'
-        return '<Lock(owner=%s)>' % name
+        return '<%s(owner=%s)>' % (self.__class__.__name__, name)
 
 #
 # Recursive lock
@@ -202,7 +202,7 @@
                 name, count = 'SomeOtherProcess', 'nonzero'
         except Exception:
             name, count = 'unknown', 'unknown'
-        return '<RLock(%s, %s)>' % (name, count)
+        return '<%s(%s, %s)>' % (self.__class__.__name__, name, count)
 
 #
 # Condition variable
@@ -243,7 +243,7 @@
                            self._woken_count._semlock._get_value())
         except Exception:
             num_waiters = 'unknown'
-        return '<Condition(%s, %s)>' % (self._lock, num_waiters)
+        return '<%s(%s, %s)>' % (self.__class__.__name__, self._lock, num_waiters)
 
     def wait(self, timeout=None):
         assert self._lock._semlock._is_mine(), \
diff --git a/Lib/multiprocessing/util.py b/Lib/multiprocessing/util.py
--- a/Lib/multiprocessing/util.py
+++ b/Lib/multiprocessing/util.py
@@ -212,10 +212,11 @@
             obj = None
 
         if obj is None:
-            return '<Finalize object, dead>'
+            return '<%s object, dead>' % self.__class__.__name__
 
-        x = '<Finalize object, callback=%s' % \
-            getattr(self._callback, '__name__', self._callback)
+        x = '<%s object, callback=%s' % (
+                self.__class__.__name__,
+                getattr(self._callback, '__name__', self._callback))
         if self._args:
             x += ', args=' + str(self._args)
         if self._kwargs:
diff --git a/Lib/pydoc.py b/Lib/pydoc.py
--- a/Lib/pydoc.py
+++ b/Lib/pydoc.py
@@ -1811,7 +1811,8 @@
         if inspect.stack()[1][3] == '?':
             self()
             return ''
-        return '<pydoc.Helper instance>'
+        return '<%s.%s instance>' % (self.__class__.__module__,
+                                     self.__class__.__qualname__)
 
     _GoInteractive = object()
     def __call__(self, request=_GoInteractive):
diff --git a/Lib/subprocess.py b/Lib/subprocess.py
--- a/Lib/subprocess.py
+++ b/Lib/subprocess.py
@@ -464,7 +464,7 @@
             raise ValueError("already closed")
 
         def __repr__(self):
-            return "Handle(%d)" % int(self)
+            return "%s(%d)" % (self.__class__.__name__, int(self))
 
         __del__ = Close
         __str__ = __repr__
diff --git a/Lib/urllib/parse.py b/Lib/urllib/parse.py
--- a/Lib/urllib/parse.py
+++ b/Lib/urllib/parse.py
@@ -641,7 +641,7 @@
 
     def __repr__(self):
         # Without this, will just display as a defaultdict
-        return "<Quoter %r>" % dict(self)
+        return "<%s %r>" % (self.__class__.__name__, dict(self))
 
     def __missing__(self, b):
         # Handle a cache miss. Store quoted string in cache and return.
diff --git a/Lib/uuid.py b/Lib/uuid.py
--- a/Lib/uuid.py
+++ b/Lib/uuid.py
@@ -222,7 +222,7 @@
         return self.int
 
     def __repr__(self):
-        return 'UUID(%r)' % str(self)
+        return '%s(%r)' % (self.__class__.__name__, str(self))
 
     def __setattr__(self, name, value):
         raise TypeError('UUID objects are immutable')
diff --git a/Lib/weakref.py b/Lib/weakref.py
--- a/Lib/weakref.py
+++ b/Lib/weakref.py
@@ -144,7 +144,7 @@
         return o is not None
 
     def __repr__(self):
-        return "<WeakValueDictionary at %#x>" % id(self)
+        return "<%s at %#x>" % (self.__class__.__name__, id(self))
 
     def __setitem__(self, key, value):
         if self._pending_removals:
@@ -348,7 +348,7 @@
         return len(self.data) - len(self._pending_removals)
 
     def __repr__(self):
-        return "<WeakKeyDictionary at %#x>" % id(self)
+        return "<%s at %#x>" % (self.__class__.__name__, id(self))
 
     def __setitem__(self, key, value):
         self.data[ref(key, self._remove)] = value
diff --git a/Lib/wsgiref/headers.py b/Lib/wsgiref/headers.py
--- a/Lib/wsgiref/headers.py
+++ b/Lib/wsgiref/headers.py
@@ -131,7 +131,7 @@
         return self._headers[:]
 
     def __repr__(self):
-        return "Headers(%r)" % self._headers
+        return "%s(%r)" % (self.__class__.__name__, self._headers)
 
     def __str__(self):
         """str() returns the formatted headers, complete with end line,
diff --git a/Lib/xml/dom/minidom.py b/Lib/xml/dom/minidom.py
--- a/Lib/xml/dom/minidom.py
+++ b/Lib/xml/dom/minidom.py
@@ -648,9 +648,10 @@
 
     def __repr__(self):
         if self.namespace:
-            return "<TypeInfo %r (from %r)>" % (self.name, self.namespace)
+            return "<%s %r (from %r)>" % (self.__class__.__name__, self.name,
+                                          self.namespace)
         else:
-            return "<TypeInfo %r>" % self.name
+            return "<%s %r>" % (self.__class__.__name__, self.name)
 
     def _get_name(self):
         return self.name
diff --git a/Lib/xml/etree/ElementTree.py b/Lib/xml/etree/ElementTree.py
--- a/Lib/xml/etree/ElementTree.py
+++ b/Lib/xml/etree/ElementTree.py
@@ -174,7 +174,7 @@
         self._children = []
 
     def __repr__(self):
-        return "<Element %s at 0x%x>" % (repr(self.tag), id(self))
+        return "<%s %r at %#x>" % (self.__class__.__name__, self.tag, id(self))
 
     def makeelement(self, tag, attrib):
         """Create a new element with the same type.
@@ -509,7 +509,7 @@
     def __str__(self):
         return self.text
     def __repr__(self):
-        return '<QName %r>' % (self.text,)
+        return '<%s %r>' % (self.__class__.__name__, self.text)
     def __hash__(self):
         return hash(self.text)
     def __le__(self, other):
diff --git a/Lib/xmlrpc/client.py b/Lib/xmlrpc/client.py
--- a/Lib/xmlrpc/client.py
+++ b/Lib/xmlrpc/client.py
@@ -207,8 +207,8 @@
         self.headers = headers
     def __repr__(self):
         return (
-            "<ProtocolError for %s: %s %s>" %
-            (self.url, self.errcode, self.errmsg)
+            "<%s for %s: %s %s>" %
+            (self.__class__.__name__, self.url, self.errcode, self.errmsg)
             )
 
 ##
@@ -236,7 +236,8 @@
         self.faultCode = faultCode
         self.faultString = faultString
     def __repr__(self):
-        return "<Fault %s: %r>" % (self.faultCode, self.faultString)
+        return "<%s %s: %r>" % (self.__class__.__name__,
+                                self.faultCode, self.faultString)
 
 # --------------------------------------------------------------------
 # Special values
@@ -354,7 +355,7 @@
         return self.value
 
     def __repr__(self):
-        return "<DateTime %r at %#x>" % (self.value, id(self))
+        return "<%s %r at %#x>" % (self.__class__.__name__, self.value, id(self))
 
     def decode(self, data):
         self.value = str(data).strip()
@@ -846,7 +847,7 @@
         self.__call_list = []
 
     def __repr__(self):
-        return "<MultiCall at %#x>" % id(self)
+        return "<%s at %#x>" % (self.__class__.__name__, id(self))
 
     __str__ = __repr__
 
@@ -1426,8 +1427,8 @@
 
     def __repr__(self):
         return (
-            "<ServerProxy for %s%s>" %
-            (self.__host, self.__handler)
+            "<%s for %s%s>" %
+            (self.__class__.__name__, self.__host, self.__handler)
             )
 
     __str__ = __repr__
diff --git a/Misc/NEWS b/Misc/NEWS
--- a/Misc/NEWS
+++ b/Misc/NEWS
@@ -108,6 +108,9 @@
 Library
 -------
 
+- Issue #22033: Reprs of most Python implemened classes now contain actual
+  class name instead of hardcoded one.
+
 - Issue #21947: The dis module can now disassemble generator-iterator
   objects based on their gi_code attribute. Patch by Clement Rouault.
 

-- 
Repository URL: http://hg.python.org/cpython


More information about the Python-checkins mailing list