How Do You Replace Variables With Their Values?

Chris Angelico rosuav at gmail.com
Fri Jul 12 01:07:46 EDT 2019


On Fri, Jul 12, 2019 at 2:30 PM Aldwin Pollefeyt
<aldwinaldwindev at gmail.com> wrote:
>
> Wow, I'm so sorry I answered on the question : "How do you replace a
> variable with its value". For what i understood with the example values,
> CrazyVideoGamez wants 3 variables named like the meal-names in dictionary.
> Yes, it's not secure unless you work with your own dataset (just like
> sending your own created commands with set=True in subprocess). Yes there
> might be better solutions for the real problem. But maybe the user really
> has a purpose for it, in a secure environment with own datatset, it's a
> valid answer for "How do you replace a variable with its value".
>

What you gave was dangerous advice, and yes, there IS a better
solution - and an easier one. If you want to create variables
dynamically, then just create them!

for meal, parts in dinner.items():
    globals()[meal.replace(' ','_')] = dinner[meal]

Python has a rich set of metaprogramming tools. Don't just always
reach for exec and caveat it with "it's okay if you trust everything".

ChrisA



More information about the Python-list mailing list