1

Let's say I have a function that can take various kinds of parameter values, but I don't want to (as a constraint) pass arguments explicitly. Instead, I want to pass them as a string.:

def func(param)
   return param+param

a = 'param=4'
func(<do something to a>(a))

>>8

Is this possible in python?

I want to use this idea in Django to create Query filters based on GET parameters in a dictionary and then just chain them using their keys.

lookup_dic = {'user': 'author=user',
              'draft': 'Q(publish_date_lte=timezone.now())|
                        Q(publish_date_isnull=True)'}

Based on whether the user and draft keywords are passed in the GET parameters, this would be read out like:

queryset.objects.filter(author=user).filter(Q(publish_date_lte=timezone.now())|
                                           Q(publish_date_isnull=True))

I understand that I can do this by replacing the author=user by Q(author__name=user), but I wanted to know if this string comprehension feature is implemented in python in general?

2 Answers 2

1

Use eval

def func(param=0):
    return param+param

a = 'param=4'
eval('func(' + a +')')
Sign up to request clarification or add additional context in comments.

1 Comment

I was looking for something of the tune of func(eval(a)) (Which of course, does not work).
1

Are you looking for this?

def func(param):
    return param + param


a = 'param=4'
parameter, value = a.split("=")
print(func(**{parameter: int(value)}))
# >> 8

Comments

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.