Comprehensive Python Cheatsheet (2018)
gto76.github.io
gto76.github.io
However, when I start development of new code I always use a script that starts off with traceback and pdb, something like this:
#!/usr/bin/env python
import traceback
import pdb
import sys
def main():
# some WIP code that maybe raises an exception
raise BaseException("oh no, exception!")
return 0
if __name__ == "__main__":
try:
ret = main()
except:
traceback.print_exc()
pdb.post_mortem()
sys.exit(ret)
This means that whenever an uncaught exception gets raised, I immediately get told what happened (full backtrace) plus I get dumped into the debugger, from where I can inspect why this happened. I liberally sprinkle assert()s through my code, so this gives me a good edit-run-debug cycle to work with.python -i script.py
I've programmed Python for years and never knew this. I'm not sure how well this handles errors. Tab complete works, only thing that is missing is needing to wrap help(<func>) to see signatures. I'm enjoying the standard lib interpreter.
If you're on linux it's not _that_ bad without it since the shell sort of acts like the notebook (with an equally horrible markup language). The help() and tab-complete and _ __ ___ for last 3 values works, time python <file>.py can benchmark, -i or pdb.set_trace does the debugging. It doesn't keep a persistent history though so the workflow is sort of different.
So I use both, particularly for plots and images knowing IPython is very helpful for working with the notebooks.
(self, key, default) => self[key] = (key in self ? self[key] : default)
I'd prefer something like "dict#createifnotexists", but better. no_duplicates = list(dict.fromkeys(<list>))
instead of no_duplicates = list(set(<list>))
? >>> list(dict.fromkeys([3, 2, 1]))
[3, 2, 1]
>>> list(set([3, 2, 1]))
[1, 2, 3]The reason being that the ordered dict ends up being faster than non-ordered, and people will rely on this implementation detail, so they added it to the spec to make that okay.
This talk is definitely worth a watch yes :)
> What I took from that is the implementation does preserve order but it isn't guaranteed yet and in theory it could change.
This was the case for python 3.6, but starting from Python 3.7 ordering is guaranteed [1]:
Changed in version 3.7: Dictionary order is guaranteed to be insertion order.
[1] https://docs.python.org/3.7/library/stdtypes.html#dict-viewsHis talks are good, except that every time he asks a stupid rhetorical question of the audience I’m overwhelmed with the urge to wang¹ a tomato at him.
[1] https://docs.python.org/2/tutorial/datastructures.html#dicti...
Performing list(d) on a dictionary returns a list of all the keys used in the dictionary, in
insertion order ...EDIT: clicking through to GitHub, the date is clearly not up-to-date, so this might have been added later.
That's why there's OrderredDict.
Unless the language explicitly says that dicts hold their order, even if they do, it's an implementation detail, and it should not be relied upon.
(Dicts in 3.7 and ordered dicts)
https://stackoverflow.com/questions/50872498/will-ordereddic...
if __name__ == '__main__':
main()
is better as if __name__ == '__main__':
sys.exit( main() )Treating docstrings as an actual reflectable part of a class/function and not just "comments to be ignored by a parser" is brilliant.
With Python, many times I vaguely know something but dunno what it is exactly. This cheatsheet solves that!
With Python, many times I vaguely know something but dunno what it is exactly. This cheatsheet solves that!
>>> from server.db import db
>>> help(db)
help on Client in module google.cloud.firestore_v1beta1.client object:
class Client(google.cloud.client.ClientWithProject)
| Client(project=None, credentials=None, database='(default)')
|
| Client for interacting with Google Cloud Firestore API.
|
| .. note::
|
| Since the Cloud Firestore API requires the gRPC transport, no
| ``_http`` argument is accepted by this class.
...Example: Suppose you didn't know that re was what you needed for regular expression, or suppose you forgot how iterators work etc.
Get names and types of a Python module's attributes:
https://jugad2.blogspot.com/2016/10/get-names-and-types-of-p...
and the same recipe on ActiveState Code (from where you can download the Python code for the recipe):
https://code.activestate.com/recipes/580705-get-names-and-ty...
Compare the R vector page: https://stat.ethz.ch/R-manual/R-devel/library/base/html/vect...
To the equivalent python documentation: https://docs.python.org/3/tutorial/datastructures.html
Also, for me the main link won't actually display and I can't be bothered to track down why, but the Github source (https://github.com/gto76/python-cheatsheet) displays just fine.
If you were to use e.g. org-mode for the source document, you could easily export to HTML automatically when the file is saved.
You could also easily use a git hook to run e.g. pandoc to convert md to HTML automatically.
There are many ways of automatically exporting HTML when you save the md source file. Please use one.
If you are going to write a cheatsheet with samples of Python code, why not write it in valid Python?
This is clearly aimed at beginners as the samples are or very basic things, yet this is going to be confusing to them as they will think that `<list>` is syntax.
Have a look at the Python docs for much better ways of doing this
The Python docs (example here[1]) on the other hand limit themselves to {}, [] and () to differentiate between dicts, lists and tuples, but doesn't really differentiate between these and the more generalized notions of collections/iterators/element, etc.
As someone who codes in statically typed languages and has an intuitive sense of upcasting / downcasting / contravariance / covariance, this level of precision makes sense to me and enhances my appreciation for Python types.
That said, I've also been writing Python professionally since 2005 so I'm comfortable with not worrying too much about types in Python -- with dynamic typing things just work as long as they have the right shape and behavior.
[1] https://docs.python.org/3/library/threading.html#threading.T...
For me this is the best quick reference for Python (2.7 unfortunately): http://rgruet.free.fr/PQR27/PQR2.7.html
no_duplicates = list(dict.fromkeys(<list>)) no_duplicates = set(<list>)That being said, and not that it should ever make a difference, list(set(<list>)) is 2-3 times faster than list(dict.fromkeys(<list>))
Are there any available for Ruby or Linux?
MIND = BLOWN <iter> = (i+5 for i in range(10)) # (5, 6, ..., 14)
really a generator expression?<iter> = ( f(i) for i in <gen>)
where f() is some function of i.