[Tutor] Beginners question
Mats Wichmann
mats at wichmann.us
Sun Apr 5 09:44:05 EDT 2020
On 4/4/20 7:53 PM, Alex Kleider wrote:
>
> I've been surprised not to have seen, in this thread, any mention made
> of the following use pattern:
>
> print("{first} {last}, {address}, {city}, {province}, {code},
> {country}".format(**record))
>
> Is this possible with any of the other (is it three) formatting methods?
> It's a pattern I've come to appreciate very very much.
>
> PS it is of course assumed that 'record' is a dict with values for keys
> 'first', 'last', ....
I deal with a project codebase which does tons of that with %-style
formatting in building up tests - the reasoning being that because some
information is not known until runtime, constructing the test code or
the expected responses is deferred until runtime, when things like
path-to-the-test-directory are finally known. Example:
sub1_f1a_out = os.path.join('sub1', 'f1a.out')
sub2_f1b_out = os.path.join('sub2', 'f1b.out')
sub1_f2a_out = os.path.join('sub1', 'f2a.out')
sub2_f2b_out = os.path.join('sub2', 'f2b.out')
expect = test.wrap_stdout("""\
batch_build(["%(sub1_f1a_out)s", "%(sub2_f1b_out)s"], ["f1a.in", "f1b.in"])
batch_build(["%(sub1_f2a_out)s", "%(sub2_f2b_out)s"], ["f2a.in", "f2b.in"])
""" % locals())
to understand this you need to know that locals() returns a dictionary
of the values in the current local scope:
>>> type(locals())
<class 'dict'>
>>> greet = "Hello"
>>> locals()
{'__name__': '__main__', '__doc__': None, '__package__': None,
'__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__':
None, '__annotations__': {}, '__builtins__': <module 'builtins'
(built-in)>, 'x': 'Hello', 'greet': 'Hello'}
and that %(key)s is the placeholder in the string to be substituted
with the value picked from the dict.
Frankly, there are other ways to solve this problem and this approach
always makes me mildly queasy when I look at it. But is it possible? Yes.
More information about the Tutor
mailing list