Beruflich Dokumente
Kultur Dokumente
PEP: 3140
Title: str(container) should call str(item), not repr(item)
Version: 226bf9ef3c9e
Last-Modified: 20090105 01:20:25 +0000 (Mon, 05 Jan 2009)
Author: Mustapha Elmekki
Discussions-To: <python3000 at python.org>
Status: Rejected
Type: Standards Track
Content-Type: text/plain
Created: 27May2008
Post-History: 28May2008
Abstract
This document discusses the advantages and disadvantages of the
current implementation of str(container). It also discusses the
pros and cons of a different approach - to call str(item) instead
of repr(item).
Motivation
Currently str(container) calls repr on items. Arguments for it:
customize free license pdfcrowd.com
-- containers refuse to guess what the user wants to see on
str(container) - surroundings, delimiters, and so on;
-- repr(item) usually displays type information - apostrophes
around strings, class names, etc.
Arguments against:
-- it's illogical; str() is expected to call __str__ if it exists,
not __repr__;
-- there is no standard way to print a container's content calling
items' __str__, that's inconvenient in cases where __str__ and
__repr__ return different results;
-- repr(item) sometimes do wrong things (hex-escapes non-ASCII
strings, e.g.)
Current situation
Most container types (tuples, lists, dicts, sets, etc.) do not
implement __str__ method, so str(container) calls
container.__repr__, and container.__repr__, once called, forgets
it is called from str and always calls repr on the container's
items.
>>> print(['тест'])
['\xd4\xc5\xd3\xd4']
One of the motivations for PEP 3138 is that neither repr nor str
will allow the sensible printing of dicts whose keys are non-ASCII
text strings. Now that Unicode identifiers are allowed, it
includes Python's own attribute dicts. This also includes JSON
serialization (and caused some hoops for the json lib).
PEP 3138 proposes to fix this by breaking the "repr is safe ASCII"
invariant, and changing the way repr (which is used for
persistence) outputs some objects, with system-dependent failures.
class Test:
def __str__(self):
return "STR"
def __repr__(self):
return "REPR"
test = Test()
print(test)
customize free license pdfcrowd.com
print(test)
print(repr(test))
print([test])
print(str([test]))
to print
STR
REPR
[STR]
[STR]
STR
REPR
[REPR]
[REPR]
A different approach - call str(item)
For example, with numbers it is often only the value that people
care about.
But putting the value in a list forces users to read the type
information, exactly as if repr had been called for the benefit of
a machine:
After this change, the type information would not clutter the str
output:
Backward compatibility
In those cases where type information is more important than
usual, it will still be possible to get the current results by
calling repr explicitly.
End Note
This package is not yet complete, but it has enough in it to be useful for writing plug-ins for GIMP. If you write any plug-
ins that might be useful as examples,