Quantcast
Channel: Planet Python
Viewing all articles
Browse latest Browse all 22462

Marc-André Lemburg: Simplifying print() string formatting

$
0
0

A couple of weeks ago, there was a lengthy discussion on the python-ideas mailing list about how to simplify string formatting in Python 3, esp. related to print() output.

Several proposals were made and three PEP came out of the discussion:

When will this be available ?

The accepted PEP 498 will only make it into Python 3.6, which will take another (around) 18 months to be released.

However, you don’t really have to wait that long and it’s even possible to come close to the proposal in Python 2.7, if all you want is print such strings.

With print() being a function in Python 3 and optionally in Python 2.7, you can use simple helper functions to define your formatting functions:

# For Python 2 you need to make print a function first:
from __future__ import print_function
import sys

# Keep a reference to the native print() function
_orig_print = print # Use .format() as basis for print() def fprint(template, *args, **kws): caller = sys._getframe(1) context = caller.f_locals _orig_print(template.format(**context), *args, **kws) # Use C-style %-formatting as basis for print() def printf(template, *args, **kws): caller = sys._getframe(1) context = caller.f_locals _orig_print(template % context, *args, **kws) # Examples: a = 1 fprint('a = {a}') printf('a = %(a)s') # Let's use fprint() as standard print() in this module: print = fprint b = 3 print('b = {b}')

Running the above script, gives the expected output:

a = 1
a = 1
b = 3

Both in Python 2.7 and Python 3, and now rather than later.

Good idea or bad ?

Whether it’s a good idea to have code implicitly look up locals is a good idea remains to be seen. I generally prefer to write things down explicitly - even if there is a bit of duplication.

Tricks such as the above certainly make it harder to see where variables are being used and can thus be a source of error. Then again, the formatting routines will complain loudly if they cannot find a variable, instead of just generating empty strings as output:

>>> printf('%(c)s')
Traceback (most recent call last):
  File "", line 1, in 
  File "myprint.py", line 23, in printf
    _orig_print(template % context, *args, **kws)
KeyError: 'c'

Enjoy,

Marc-André


Viewing all articles
Browse latest Browse all 22462

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>