Comprehension complexity

Remember that there's no limit to the complexity of the expression you can use in any of the comprehensions. For the sake of your fellow programmers, though, you should avoid going overboard. Instead, extract complex expressions into separate functions to preserve readability. The following is close to the limit of being reasonable for a dictionary comprehension:

>>> import os
>>> import glob
>>> file_sizes = {os.path.realpath(p): os.stat(p).st_size for p in
glob.glob('*.py')}

>>> pp(file_sizes)
{'/Users/pyfund/examples/exceptional.py': 400,
'/Users/pyfund/examples/keypress.py': 778,
'/Users/pyfund/examples/scopes.py': 133,
'/Users/pyfund/examples/words.py': 1185}

This uses the glob module to find all of the Python source files in a directory. It then creates a dictionary of paths to file sizes from those files.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset