__str__ vs. __repr__
skaller at maxtal.com.au
Fri Nov 12 05:31:21 EST 1999
> Quoth "Tim Peters" <tim_one at email.msn.com>:
> | Let me back off to what repr and str "should do":
> | repr(obj) should return a string such that
> | eval(repr(obj)) == obj
FYI: Viperi (my python interpreter) contains an extension, a function
which provides these semantics for a much wider
class of types than CPython 1.5.2, including: modules, classes,
and functions, provided all the attributes are themselves
'erepr'able. Erepr will not handle (native) file objects.
There is, however, a caveat.
returns a string representing the definition of the function f.
However, evaluating the string will NOT work correctly,
unless the globals is correctly set, something like:
is required. Similarly for classes.
Oh yes, I forgot to mention that all Viper statements are also
expressions, the 'e' in erepr means 'expression'.
In fact, given an expression, such as
x + 1
then, erepr applied to this expression yields a string
'x + 1'
There is currently no way to define such an expression in Viperi.
[A 'lazy' or 'defered' evaluation control is under consideration]
However, it has facilities for partial evaluation, they're just
disabled for Python compatibility. For example, with partial
evaluation enabled, the result of:
y = 1
z = x + y
is that x is an _expression_ whose value is
x + 1
In Viper, expressions are THE first class type. All other types
are cases of expressions (including statements, objects, and values
of almost all kinds -- slices are not expressions at the moment).
You may be wondering how this works. The answer is that Viperi does not
use bytecode, it executes the 'Abstract Syntax Tree' directly.
Consequently, the original code can be recovered. (without comments,
or the original formatting, of course).
Note that this will NOT work if the object has been bound,
that is, if names have been replaced by numeric indexes.
(And, it will not work in compiled code either, for the same reason:
bound or compiled code is the 'moral equivalent' of python bytecode)
| I'd go further and formalize a property that's currently honored but
> | implicitly: the string returned by repr should contain only characters c
> | such that
Viper repr functions uses only 'printable characters' in the range
of ISO10646, plus space. (i.e. printable ASCII characters plus space).
All other codes are represented either using \n (and related specials)
or using \uXXXX or \uXXXXXXXX encoding. [There will be a
python compatibility switch to force use of python lexicology]
John Skaller, mailto:skaller at maxtal.com.au
1/10 Toxteth Rd Glebe NSW 2037 Australia
More information about the Python-list