Help me abstract this (and stop me from using eval)

D

Daniel Klein

Hi!

I've got import scripts for a bunch of csv files into an sqlite database. Ihave one csv file per language. I don't write directly to the sqlite db; this is a django app and I'm creating items in my django models.

My script (scripts, unfortunately) work just fine, but it feels beyond stupid to have one script per language--importgerman, importfrench etc. The problem is that I don't know how to abstract which language I'm currently writing to. Here's the central loop:

http://pastebin.com/NBT6feNB

This is for the Polish version of the script, of course, the one that gets fed pl.csv. For those unfamiliar with django, I need to first retrieve the message instance for issue name / long text / short text / category name. Hence the ugly tempmes stuff.

So ideally I would tell the script which language I'm currently importing and based on that it would write to the appropriate text fields. But I don'tknow how to abstract this:

tempmes.polish = row[1]

Well, I do. Like this:

eval("tempmes." + language + " = row[1]")

But... eval is evil, no? There's got to be a better way?
 
K

Kwpolska

tempmes.polish = row[1]

Well, I do. Like this:

eval("tempmes." + language + " = row[1]")

But... eval is evil, no? There's got to be a better way?

Easy.

tempmes = myissue.name
language = 'polish'
setattr(tempmes, language, row[1])
tempmes.save()
 
S

Steven D'Aprano

So ideally I would tell the script which language I'm currently
importing and based on that it would write to the appropriate text
fields. But I don't know how to abstract this:

tempmes.polish = row[1]

Well, I do. Like this:

eval("tempmes." + language + " = row[1]")

setattr(tempmes, language, row[1])
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,770
Messages
2,569,583
Members
45,075
Latest member
MakersCBDBloodSupport

Latest Threads

Top