Python keyword workaround

2007-03-23Comments

I was writing a simple tool and wanted to pass it from and to parameters. As usual, I used the optparse module to extract these parameters from the command line.

Spot the syntax error
def do_something(from_here, to_here):
    ....

from optparse import OptionParser
parser = OptionParser()
parser.add_option("--from")
parser.add_option("--to")

opts, files = parser.parse_args()
do_something(opts.from, opts.to)

This code won’t work because from is a keyword (it’s used to qualify module imports).

    do_something(opts.from, opts.to)
                         ^
SyntaxError: invalid syntax

One pragmatic way round this would be to change the command line parameters.

parser.add_option("--start")
parser.add_option("--finish")

I didn’t want to do that, so here’s another.

do_something(getattr(opts, "from"), opts.to)