Python - wise tricks
There’s a discussion on reddit about tricks older programmers would like younger ones to know. A heavy bias may be present (the older ones wanting to keep the younger in check), but my digest reads quite reasonable - so naturally I want to write it down for later reference:
- Use Python 3.6, there are some significant improvements over 2.7 - like enums and fstrings (I would switch to 3.6 just for fstrings, TBH)
.close()is often a code smell - you probably should be using a with block
virtualenvfor every project - don’t install python packages at the system level. This keeps your project environment isolated and reproducible
- Use the
csvmodule for CSVs (you’d be surprised…)
- Don’t nest comprehensions, it makes your code hard to read (this one from the Google style guide, IIRC)
- If you need a counter along with the items from the thing you’re looping over, use
- If you’re using an IDE (as a Vim user I say you’re crazy if you’re not using Pycharm with Ideavim) take the time to learn it’s features. Especially how to use the debugger, set breakpoints, and step through code
- Developing with a REPL like ipython or Jupyter alongside your IDE can be very productive. I am often jumping back and forth between them. Writing pure functions makes them easy to test / develop / use in the REPL. ipython and Jupyter have helpful magics like
- Use destructuring assignment, not indices, for multiple assignment
first, second, *_ = (1,2,3,4)
**kwargsunless you know you need them - it makes your function signatures hard to read, and code-completion less helpful
- Use a linter tool like pyflakes or pylint on everything you write. Integrate them into your IDE. They will force you to be a better programmer.
- write unit tests!