2

I have a basic question on python functions and parameters

Given this function:

def findArticleWithAttr(tableattrib, user_url_input):
    articles = Something.objects.filter(tableattrib=user_url_input) 

I call the function with:

findArticleWithAttr(attribute1, userinput1)

tableattrib is not set by findArticleWithAttr attribute1 and just takes the latter (userinput1) parameter and replaces it.

How can i make python set both parameters in the equation?

Rob Wouters
  • 15,797
  • 3
  • 42
  • 36
Jurudocs
  • 8,595
  • 19
  • 64
  • 88
  • Not sure of what are you trying here, but this `Something.objects.filter(tableattrib=user_url_input)` doesn't seem correct. What you're doing in there is passing `user_url_input` to an argument called `tableattrib` for the method `.filter`. Not sure, but I think that's not what you want... Also, what's this? Django? – Ricardo Cárdenes Jan 04 '12 at 23:34
  • @RicardoCárdenes: He's trying to allow the attribute by which to filter to be specified as an argument to `findArticleWithAttr`. Obviously this doesn't work, as `tableattrib` is treated as a keyword identifier rather than a variable identifier in this syntax. – Will Vousden Jan 04 '12 at 23:36
  • Hi...yes you are right... its django...what i want is to define the parameter and attribute from an outside function...thanks for your comment – Jurudocs Jan 04 '12 at 23:37
  • thanks @ Will that's what i want ;-P is that possible? – Jurudocs Jan 04 '12 at 23:39

1 Answers1

8

You could use the ** double-splat operator:

def findArticleWithAttr(tableattrib, user_url_input):
    articles = Something.objects.filter(**{tableattrib : user_url_input}) 

Basically, the ** operator makes

func(**{'foo' : 'bar'})

equivalent to

func(foo = 'bar')

It allows you to call a function with arbitrary keyword arguments.

unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677
  • 2
    For more information about this method of passing parameters, look at "unpacking" or this relevant SO question: http://stackoverflow.com/questions/334655/passing-a-dictionary-to-a-function-in-python-as-keyword-parameters – aganders3 Jan 04 '12 at 23:37