[Python-ideas] string.format() default variable assignment

Chris Angelico rosuav at gmail.com
Fri Mar 1 12:07:19 EST 2013


On Sat, Mar 2, 2013 at 3:55 AM, 김용빈 <kybinz at gmail.com> wrote:
> why we bother with '{variable}'.format(variable=variable) ?
> can we just '{variable}.format()' ?
>
> if variable is exist, then assign it.
> if variable is not exist, then raise error
>
> I am not language expert. so sorry if this is not a good idea, or already
> discussed.

You're asking for a facility whereby variables magically get pulled
from the caller's scope. Let me put it to you another way:

def func1():
   return foo + " world"

def func2():
    foo = "Hello"
    print("func1 returns: "+func1())

func2()

Will this work? If not, why not?

There are ways around this; you can, for instance, pass locals() to format():
'{variable}'.format(**locals())

But this is massive overkill and can unexpectedly expose a whole lot
more than you wanted (an issue if you accept a format string from an
untrusted source). Generally, it's best to be explicit. You can avoid
repeating the name so much by using positional parameters instead:

'{0}'.format(variable)

Of course, this has its own considerations. But at least it isn't magical. :)

ChrisA



More information about the Python-list mailing list