Hacker News new | ask | show | jobs
by danudey 3993 days ago
Explicit is better than implicit. We have a lot of older format strings (from before .format()) that look like this:

"%s %s: Caught %s in %s (%s)"

As compared to:

"{date} {processname}: Caught {except_type} in {func} ({module})"

It's more typing, sure, but it's more typing once, and it makes it extremely obvious what the string is going to look like and what each field is without having to read the arguments.

Then using named parameters means you can easily see what's supposed to be what:

% (ts, proc['name'], ex.type, fn, __name__)

versus:

.format(date=ts, processname=proc['name'], except_type=ex, func=fn, module=__name__)

Lastly, it lets you make quick modifications to strings without having to deal with inserting it at the correct place in a format string of 10 items. You can add in a new field in the middle, at the start, or both, and be able to just add newfield=var at the end of the format() call without having to insert it the correct spot, or in multiple places. Also, removing variables from the format string and not from the parameter list which removes a class of subtle, annoying bugs that tend to be caught after deployment.

If you're looking for some major revolution as to why this is the demonstrably better choice and will revolutionize how you put strings together, you won't find it. What this offers is a lot of power, convenience, readability, and maintainability in exchange for a negligible increase in typing.

1 comments

Sure, with old syntax you can do it as well:

>>> print('%(language)s has %(number)03d quote types.' %

... {'language': "Python", "number": 2})