How Do You Replace Variables With Their Values?

Ian Kelly ian.g.kelly at gmail.com
Sun Jul 14 15:43:19 EDT 2019


On Thu, Jul 11, 2019 at 11:10 PM Chris Angelico <rosuav at gmail.com> wrote:
>
> 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".

To be fair, if dinner is untrusted then this new version is still unsafe.
You've just allowed it to shadow any global or built-in it wants to.



More information about the Python-list mailing list