__repr__ policy problem: should module be prefixed to output?
Pearu Peterson
pearu at cens.ioc.ee
Fri Dec 15 14:54:58 EST 2000
On Fri, 15 Dec 2000, Alex Martelli wrote:
> "Per Kraulis" <per at sbc.su.se> wrote in message
> news:3A3A3A6D.2C3B1A91 at sbc.su.se...
> > The problem is that Alt 1 is appropriate in the context of "import
> > crng", while Alt 2 is better when having done "from crng import *".
>
> If it was only the latter, it would not be worth supporting except
> for those very rare modules that are _designed_ to be from-import-*'ed.
>
> But a more reasonable usage, such as:
>
> from themodule import specificthing, anothergoodie, classname
>
> would also favour repr strings of the form 'classname(avalue)' over
> 'themodule.classname(avalue)'.
>
> Existing modules seem to do it both ways, so it's hard to
> find specific precedents for guidance.
>
> One thing favouring the 'undecorated' form is that an eval
> _using the module's dictionary as global-dictionary_ should
> then work anyway (as well as string-manipulations before
> eval, which are of course possible in either case).
>
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
Now in python session:
>>> import foo
>>> foo.A(3)
foo.A(3)
>>> eval(repr(foo.A(3)))
foo.A(3)
and in another python session:
>>> from foo import *
>>> A(3)
foo.A(3)
>>> eval(repr(A(3)))
foo.A(3)
And the answer to the original question is Yes.
Regards,
Pearu
More information about the Python-list
mailing list