0

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.

7
  • 1
    I don't understand what you mean Variable Variable. But if you want to use string to create variable then use dictionary - name = 'John' variable[name] = name Commented May 3, 2019 at 8:53
  • you could use a dictionary: my_vars = {"name": "John", ...} with as many keys as you want/need, and access it with my_vars[variable_name] Commented May 3, 2019 at 8:54
  • it's the concept of using variable as variable name, in this case $$variable_name will be John Commented May 3, 2019 at 8:55
  • use dictionary. It is prefered method. Commented May 3, 2019 at 8:56
  • What are you actually trying to do? Commented May 3, 2019 at 9:04

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

so, using List is the only way out?
More like, dictionaries.
The OP is asking about Django Templates which is presumably django template language, not python
@Sayse Variable variables are also not supported in the Django templating language, as per the docs. I'd be surprised if it did, it'd go against the consistency with the Python language found in Django.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.