4

I am running i.maxlik in python - attempting to automate a processing chain. I use the command:

grass.run_command('i.maxlik', group= group, subgroup=subgroup, class='classification', sigfile = sigfile, verbose = True)

Infuriatingly, however 'class' is a python keyword and it doesn't run due to 'invalid syntax'.

Would you know a way to work around this? I have tried emailing the GRASS developer list but no response.

Regards

Becky

3 Answers 3

4

Per http://grasswiki.osgeo.org/wiki/GRASS_Python_Scripting_Library#Use_Python_reserved_keyword, add an underscore to the beginning of the argument that is a reserved word. So your command would be:

grass.run_command('i.maxlik', group= group, subgroup=subgroup, _class='classification', sigfile = sigfile, verbose = True)

3

Here is a handy Python trick that you can use to unpack a dictionary into keyword args:

def myfunc(arg1, arg2, arg3):
    print arg1, arg2, arg3

args = {"arg1": "Hello", "arg2": "World"}

myfunc(arg3=1234, **args)

Note the ** before the variable args

You can just put the class keyword into a dictionary:

args = {"class": 'classification' }

then pass it as extra keyword arguments:

grass.run_command('i.maxlik', group= group, subgroup=subgroup, sigfile = sigfile, verbose = True, **args)

Note: You can even do it inline:

myfunc(arg3=1234, **{"arg1":'Hello', "arg2":"World"})
1

You can use args and kwargs technique as suggested by Nathan W but I would avoid that unless you need it also for something else.

The preferred syntax is appending and underscore (class becomes class_):

from grass.script import run_command
...
run_command('i.maxlik', ..., class_='classification', ...)

This applies to all functions form start_command family.

Note that Eric G is right about the underscore at the beginning in case of GRASS GIS 6 but the behavior was changed recently to underscore at the end to follow Python PEP8 style guide. The underscore at the beginning will be supported for backward compatibility for some time but it will give you a warning similar to the following one:

WARNING: To run the module add underscore at the end of the option <class>
         to avoid conflict with Python keywords. Underscore at the
         beginning is depreciated.

If you think that underscore at the the end in GRASS GIS 6 would be useful for you, please create a enhancement ticket for this backwards compatibility feature request.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.