[Tutor] translating some python code to perl

Lloyd Kvam pythontutor at venix.com
Mon Oct 6 17:33:13 EDT 2003


Thanks to Danny, the Perl folks who wanted my transformed python-to-perl code
are happy.  (I just got the email saying so.)  However, I thought I should
post a followup.  I'm not sure how Danny was able to avoid typing a YIKES!
when he saw my class.

Overriding __repr__ to emit perl code is a very bad idea.  In general, you
want x = eval( repr( x)) to be true.  Clearly emitting perl code breaks
that expectation very badly.

I've mangled Danny's code slightly (e.g.sorting the dictionary keys), but if
anyone else finds the need to generate perl data from python data, this could
be a useful starting point.

####
def renderObject(obj):
	if isinstance(obj, dict):
		return renderDictionary(obj)
	elif isinstance(obj, str):
		return renderString(obj)
	raise Exception, ("I don't know how to handle %s" % obj)

def renderDictionary(d):
	rendered_items = []
	keys = d.keys()
	keys.sort()
	for key in keys:
		rendered_items.append("%s => %s," % (renderObject(key),
											renderObject(d[key])))
	return "{\n%s\n}" % (indent(rendered_items))

def renderString(s):
	return repr(s)

def indent(s):
	indented_lines = ['    ' + l for l in s]
	indented_lines = [l.replace('\n','\n    ') for l in indented_lines]
	return '\n'.join(indented_lines)

# remember to add the semicolon
print "$perl_dict = %s;" % (renderObject(pydict))
####

Danny Yoo wrote:

> 
> On Thu, 28 Aug 2003, Lloyd Kvam wrote:
> 
> 
>>This did not generate any responses, but I thought I'd post my solution
>>anyway.
>>My python code (version 2.2) follows:
>>#!/usr/bin/python
>># py2perl.py
>>'''module to handle some python to perl transformations.
>>'''
>>class Py2perl_dict(dict):
>>
>>	def __init__(self, arg):
>>	    super(Py2perl_dict, self).__init__(arg)
>>	    for key,val in self.items():
>>		if isinstance(val, dict) and not isinstance(val, Py2perl_dict):
>>		    self[key] = Py2perl_dict(val)
>>
>>	def __repr__(self):
>>	    keylist = self.keys()
>>	    keylist.sort()
>>	    return ''.join(['{',
>>                 ','.join(["%s => %s" % (repr(key),repr(self[key])) for key in keylist]),
>>                 '}'])
> 
> This code works, but also does modifications to our original dictionary.
> Seems a harsh price to pay for compatibility.  *grin*

-- 
Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358

voice:	603-443-6155
fax:	801-459-9582




More information about the Tutor mailing list