Variable Variable in django template

232 views Asked by At

view.py

variable = 'amount'
amount = 200
print(variable) #actual: 'amount' expected: 200

In such case, is it possible to use Variable Variable like PHP? in php, I could do

$variable = 'amount';
$amount = 200;
echo $$variable;

I know it might be not a good practice, but sometimes it could provide very powerful features.

Thanks.

1

There are 1 answers

4
Óscar López On

Neither Python nor Django's templates support variable variables... fortunately. It's a confusing language feature in PHP and we're better off without it - as you said, it's not even a good practice to use them.

Think of it as a bad habit in PHP that you'll be leaving behind now, even in PHP there are always better alternatives. Maybe someone thought it was a good idea at the time but modern best practices indicate otherwise.

If you feel the need for dynamic behaviour regarding variable names consider using a dictionary instead, see this post for details.