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.

Wils
  • 1,178
  • 8
  • 24
  • 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` – furas May 03 '19 at 08: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]` – Robin Zigmond May 03 '19 at 08:54
  • it's the concept of using variable as variable name, in this case $$variable_name will be John – Wils May 03 '19 at 08:55
  • use dictionary. It is prefered method. – furas May 03 '19 at 08:56
  • What are you actually trying to do? – Sayse May 03 '19 at 09:04
  • @Sayse I am switching from PHP to python, so I want to see if that's possible in python. – Wils May 03 '19 at 09:05
  • Thats a broad statement, different languages quite often have different ways of handling issues – Sayse May 03 '19 at 09:06

1 Answers1

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.

Óscar López
  • 232,561
  • 37
  • 312
  • 386
  • so, using List is the only way out? – Wils May 03 '19 at 08:57
  • 2
    More like, dictionaries. – Óscar López May 03 '19 at 08:57
  • The OP is asking about Django Templates which is presumably django template language, not python – Sayse May 03 '19 at 09:04
  • @Sayse Variable variables are also not supported in the Django templating language, as per the [docs](https://docs.djangoproject.com/en/1.7/topics/templates/). I'd be surprised if it did, it'd go against the consistency with the Python language found in Django. – Óscar López May 03 '19 at 09:20