Unidata / MetPy

MetPy is a collection of tools in Python for reading, visualizing and performing calculations with weather data.
https://unidata.github.io/MetPy/
BSD 3-Clause "New" or "Revised" License
1.26k stars 415 forks source link

"Effective Python" ideas #97

Open dopplershift opened 9 years ago

dopplershift commented 9 years ago

Been reading effective Python. Some things that might need reviewing:

(will add others as I keep reading)

dopplershift commented 7 years ago

Similar, but from a Raymond Hettinger talk (iter taking a sentinel was already on my list). This:

blocks = []
while True:
    block = f.read(32)
    if block == '':
        break
    blocks.append(block)

can be turned into:

blocks = []
for block in iter(partial(f.read, 32), ''):
    blocks.append(block)

And really:

blocks = list(iter(partial(f.read, 32), ''))

And that iter construct can be passed to things like sorted, min, max, etc.

dopplershift commented 7 years ago

Linking Ned Batchelder's talk Loop like a native so I don't lose it--it's another good reference for these kind of things.

dopplershift commented 7 years ago

Also:

  1. Can mutate dictionary while looping over it if you use .keys() rather than looping over dict directly.
  2. Construct dictionaries from iterable of pairs
  3. defaultdict
  4. vars() instead of reading class __dict__
  5. ChainMap to replace combining a bunch of dicts together
  6. Tuple unpacking to keep state in lock-step
  7. No del l[0], l.pop(0), l.insert(0, item)
  8. ignored context manager to ignore exceptions
  9. Don't check for file before removing--race condition