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?

4
  • 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? Commented Jan 4, 2012 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. Commented Jan 4, 2012 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 Commented Jan 4, 2012 at 23:37
  • thanks @ Will that's what i want ;-P is that possible? Commented Jan 4, 2012 at 23:39

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

For more information about this method of passing parameters, look at "unpacking" or this relevant SO question: stackoverflow.com/questions/334655/…

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.