Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use a string as a keyword argument?

Tags:

python

Specifically, I'm trying to use a string to arbitrairly filter the ORM. I've tried exec and eval solutions, but I'm running into walls. The code below doesn't work, but it's the best way I know how to explain where I'm trying to go

from gblocks.models import Image f = 'image__endswith="jpg"' # Would be scripted in another area, but passed as text <user input> d = Image.objects.filter(f)   #for the non-django pythonistas: d = Image.objects.filter(image__endswith="jpg") # would be the non-dynamic equivalent. 
like image 458
Issac Kelly Avatar asked May 28 '10 21:05

Issac Kelly


People also ask

How do you use keyword as string in Python?

Python in its language defines an inbuilt module “keyword” which handles certain operations related to keywords. A function “iskeyword()” checks if a string is a keyword or not. Returns true if a string is a keyword, else returns false.

How do you specify a keyword arguments in function?

Keyword arguments (or named arguments) are values that, when passed into a function, are identifiable by specific parameter names. A keyword argument is preceded by a parameter and the assignment operator, = . Keyword arguments can be likened to dictionaries in that they map a value to a keyword.

How do you create a keyword argument in Python?

The special syntax *args in function definitions in python is used to pass a variable number of arguments to a function. It is used to pass a non-key worded, variable-length argument list. The syntax is to use the symbol * to take in a variable number of arguments; by convention, it is often used with the word args.

How do you convert a string to an argument in Python?

Convert String Into Variable Name in Python Using the exec() Function. We can use the exec() function for the dynamic execution of a python statement. The exec() function takes a python statement in the form of a string as an input argument.


1 Answers

d = Image.objects.filter(**{'image__endswith': "jpg"}) 
like image 178
Ignacio Vazquez-Abrams Avatar answered Oct 03 '22 03:10

Ignacio Vazquez-Abrams