0

I've got a logging statement, something like:

get_logger().info(
    'Logger logging %s because we need to log it.' % response['foo']['bar']
)

With indentation it comes out well over 80 rows. If I could split it around the %, it would be fine.

How can I split this into multiple lines. (ideally without just putting response['foo']['bar'] into a variable)

Jones
  • 1,154
  • 1
  • 10
  • 35

3 Answers3

1
get_logger().info(
    'Logger logging %s because we need to log it.' 
    % response['foo']['bar']
)
Ivan Chaer
  • 6,980
  • 1
  • 38
  • 48
0

When using Python string formatting functionalities you can provide a tuple, not just a single value, as an input:

>>> "%d %d %d" % tuple(range(3)) # or just (0, 1, 2)
'0 1 2'

And then easily split your input tuple into multiple lines. You may, additionally, even assign the template string with percent-suffixed placeholders to a variable and use it later. An example would be:

>>> template = "The averaged temperatures of the last three days were %d, %d and %d"
>>> template % (22, 26, 23)
'The averaged temperatures of the last three days were 22, 26 and 23'

You can know more about Python string formatting in printf-style String Formatting (Python 3.5.4).

Acsor
  • 1,011
  • 2
  • 13
  • 26
0

It might be worth noting that, for logging,

get_logger().info(
    'Logger logging %s because we need to log it.' 
    % response['foo']['bar']
)

is the same as:

get_logger().info(
    'Logger logging %s because we need to log it.', 
    response['foo']['bar']
)

since the debug(), info(), etc . methods interpret *args as to be used for string formatting the message.

https://docs.python.org/2/library/logging.html#logging.Logger.debug

In general for long strings, ones that ought to wrap around column 80, use parentheses, taking advantage of python's built-in string joining:

deeplyNested = True
thing = 'feedback'
class Contrived(object):
    def __init__(self):
        if deeplyNested:
            logger.info(
                ("Sometimes there's a lot to say in %s and you need to write"
                 " longer messages than what nicely fits in the 80 column"
                 " limit."),
                thing
            )
Ryan de Kleer
  • 1,246
  • 14
  • 24