Anshul
Anshul

Reputation: 776

Using string as literal expression in function argument in Python

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?

Upvotes: 1

Views: 1479

Answers (2)

user459872
user459872

Reputation: 24582

Are you looking for this?

def func(param):
    return param + param


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

Upvotes: 1

Aritesh
Aritesh

Reputation: 2103

Use eval

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

a = 'param=4'
eval('func(' + a +')')

Upvotes: 1

Related Questions