0

Assume I have the following list:

 foo = ['a', 'b', 'c', 'd', 'e']

what is the best way to fill a field by random values from above list? I've written following code, but it doesn't work.
1. Adding this code to function tab:

import random
foo = ['a', 'b', 'c', 'd', 'e']
def randomword():
    return random.choice(foo)

2. Calling above function in Expression section:

randomword()

QGIS Says: Expression is invalid.

Parser Error: syntax error, unexpected '(', expecting $end

Eval Error: No root node! Parsing failed?

2

Looks like you just have to update the arguments and syntax for your function definition. It'll return an error, expecting the one argument for length and receiving none (Qgsfunctions take two as a minimum/default). Try:

@qgsfunction(args="auto", group='Custom')

def randomword(feature, parent):
    import random
    foo = ['a', 'b', 'c', 'd', 'e']
    return random.choice(foo)

Also, your import and variable need to all be inside the function.

With edit mode OFF, click on "New File" in the Field Calculator Functions tab, name it whatever you like, and then copy your function into that. Then you should be able to click "Load", and then it should show up in the "Custom" functions drop-down (per the Group indicated in your function parameters), not as your whatever name but by the function name randomword()

  • Thanks AlecZ. It was my type mistake for adding length argument. But using your code, i still get the error explained in above question. Also, what do u mean by "Custom" list? – ALalavi Nov 7 '17 at 18:13
  • Make sure you are clicking "LOAD" and that you can select the function from the "Custom" drop down list. If it's not in there, or it is but still doesn't run, make sure you have edit mode toggled on before you go into Field Calculator to load the func and populate the field. – AlecZ Nov 7 '17 at 18:16
  • Once it's loaded, it should just be randomword without the (), too – AlecZ Nov 7 '17 at 18:17
  • I click Load, but in Expression tab (QGIS 2.18) i don't see any "Custom" dropdown menu. There is a list just for build-in functions. I'm also in edit mode. Also, In function editor, it keeps displaying a "Saving..." message. Is it a bug? – ALalavi Nov 7 '17 at 18:26
  • 1
    Oh no it does that - sorry I forgot to mention, with edit mode OFF, create "New File", named whatever, and then copy your function into that. Then you should be able to "Load", and then it should show up in the "Custom" functions drop-down, not as your whatever name but by the function name randomword() – AlecZ Nov 7 '17 at 18:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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