Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic Keyword Arguments in Python?

Tags:

python

Does python have the ability to create dynamic keywords?

For example:

qset.filter(min_price__usd__range=(min_price, max_price)) 

I want to be able to change the usd part based on a selected currency.

like image 236
user42876 Avatar asked Dec 03 '08 16:12

user42876


People also ask

What are the keyword arguments in Python?

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 pass a keyword argument in Python?

Python has *args which allow us to pass the variable number of non keyword arguments to function. In the function, we should use an asterisk * before the parameter name to pass variable length arguments.

What are the 4 types of format arguments in calling a function in Python?

5 Types of Arguments in Python Function Definition:positional arguments. arbitrary positional arguments. arbitrary keyword arguments.

What is dynamic function in Python?

Python Code can be dynamically imported and classes can be dynamically created at run-time. Classes can be dynamically created using the type() function in Python. The type() function is used to return the type of the object. Syntax: type(object) The above syntax returns the type of object.


2 Answers

Yes, It does. Use **kwargs in a function definition.

Example:

def f(**kwargs):     print kwargs.keys()   f(a=2, b="b")     # -> ['a', 'b'] f(**{'d'+'e': 1}) # -> ['de'] 

But why do you need that?

like image 52
jfs Avatar answered Sep 18 '22 07:09

jfs


If I understand what you're asking correctly,

qset.filter(**{     'min_price_' + selected_currency + '_range' :     (min_price, max_price)}) 

does what you need.

like image 32
James Hopkin Avatar answered Sep 19 '22 07:09

James Hopkin