__repr__ policy problem: should module be prefixed to output?

Pearu Peterson pearu at cens.ioc.ee
Fri Dec 15 23:41:59 CET 2000


Hi,

On Fri, 15 Dec 2000, Pearu Peterson wrote:

> There is a solution to this repr string dilemma. For example,
> consider foo.py:
> 
> # begin of file foo.py
> class A:
>     def __init__(self,value):
>         self.value = value
>     def __repr__(self):
>         return '%s.%s(%s)'%(self.__module__,
>                             self.__class__.__name__,
>                             self.value)
> 
> exec 'import %s'%__name__   # this does the trick
>                             # (could it be done also in C extension
>                             #  modules?)
> 
> #eof foo.py

I now see several problems in this solution:
1) It does not work if 'from foo import A' is used
2) If module `foo' has local object with the name `foo', then it will be
   overwritten.
So, it is not useful solution. 2) can be avoided by the module developer
but I don't see how the problem 1) could be avoided. Any ideas?

> And the answer to the original question is Yes.

For completeness, let me give another 'bad' solution where the answer to
the original question is No.
This solution re-wraps builtin function eval (which, I am pretty sure,
will not please you). But anyway, here is the result (sources are given
at the end of this message):

Python session:
>>> import foo
Warning: Built-in function "eval" is re-wrapped
>>> foo.A(1)
A(1)
>>> eval(repr(foo.A(1)))
A(1)

Another Python session:
>>> from foo import *
Warning: Built-in function "eval" is re-wrapped
>>> A(1)
A(1)
>>> eval(repr(A(1)))
A(1)

The main problem to this solution is that different modules may define
different objects with the same name. So, for generality, the answer
should be Yes.

In conclusion, I don't have a good solution. Just these two bad ones that
might be useful only in special cases.
Are there any better solutions to the repr string dilemma?

Regards,
	Pearu

######### File evalhack.py
import sys,string
_eval = __builtins__['eval']
_register = {}
def eval(source,g=None,l=None):
    if g is None: g = globals()
    if l is None: l = g
    try: return _eval(source,g,l)
    except NameError:
        v = sys.exc_value
        o = v[0][string.find(v[0],"'")+1:-1]
        if _register.has_key(o):
            l[o] = _register[o].__dict__[o]
        return _eval(source,g,l)
eval.__doc__ = _eval.__doc__

def register(module,*objs):
    m = __import__(module)
    for o in objs:
        _register[o] = m

print 'Warning: Built-in function "eval" is re-wrapped'
__builtins__['eval'] = eval

######### EOF evalhack.py #######

######### File foo.py
class A:
    def __init__(self,value):
        self.value = value
    def __repr__(self):
        return '%s(%s)'%(self.__class__.__name__,self.value)

import evalhack
evalhack.register(__name__,'A')

######### eof foo.py




More information about the Python-list mailing list