
Comprehensive Python Cheatsheet (2018) - pizzaburek
https://gto76.github.io/python-cheatsheet/
======
gorb314
I like the basic script template that the author provides.

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.

~~~
smittywerben
This is pretty smart. When I'm making one-off scripts I use the interactive
flag

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.

~~~
ont
I use ipython for similar task. It has wrapper for 'help' function ('?' symbol
after function name), tab completion and syntax highlighting. Also it has
special %hist command for easy copy-paste code.

~~~
smittywerben
I like IPython unless working with large arrays, because of weird memory
issues I experienced (maybe they're fixed?). I miss the %run, !<cd, ls, pip>,
%timeit magic and the IPython.terminal.debugger.set_trace().

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.

------
basil-rash
Is it just me or is dict#setdefualt a terribly named function? I just learned
of it here, and I was excited that it would set the default value for the
dictionary, when instead it performs something like:

    
    
      (self, key, default) => self[key] = (key in self ? self[key] : default)
    

I'd prefer something like "dict#createifnotexists", but better.

~~~
ac29
Are you maybe looking for a defaultdict?
[https://docs.python.org/3.7/library/collections.html#collect...](https://docs.python.org/3.7/library/collections.html#collections.defaultdict)

~~~
basil-rash
I'm aware of defaultdict, but when I saw that method on dict I got excited
because I thought it meant I didn't need defaultdict anymore.

------
omegote
There are several items that are dubious at best. Why would you use

    
    
        no_duplicates    = list(dict.fromkeys(<list>))
    

instead of

    
    
        no_duplicates = list(set(<list>))
    
    ?

~~~
pizzaburek

       >>> list(dict.fromkeys([3, 2, 1]))
       [3, 2, 1]
       >>> list(set([3, 2, 1]))
       [1, 2, 3]

~~~
coldtea
Dictionaries should not be assumed to keep their orderings anyway.

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.

~~~
snicker7
As of 3.7 (3.6 for cpython), dictionaries have a deterministic order.

~~~
thro_away_n
What's the best way to write code that relies on this deterministic order and
prevent it from running incorrectly with older python versions?

~~~
b_tterc_p
Import collections.OrderedDict as you would have done beforehand. There are
still some differences between them.

(Dicts in 3.7 and ordered dicts)

[https://stackoverflow.com/questions/50872498/will-
ordereddic...](https://stackoverflow.com/questions/50872498/will-ordereddict-
become-redundant-in-python-3-7)

------
dvfjsdhgfv
Can we please change the current clickbait title (Best Python Cheatsheet
Ever!) to the original one (Comprehensive Python Cheatsheet)?

~~~
timdellinger
Agreed, although I'll note here that this was posted to /r/python under the
clickbait version of the title, so the HN submitter was likely just passing it
on from there.

------
gjvc

        if __name__ == '__main__':
            main()
    

is better as

    
    
        if __name__ == '__main__':
            sys.exit( main() )

~~~
Nanocurrency
For those wondering why, like I did, here's why:
[https://stackoverflow.com/questions/5280203/what-does-
this-m...](https://stackoverflow.com/questions/5280203/what-does-this-mean-
exit-main)

------
avip
Very good page. But the best python cheat sheet is _help(the_thing)_. python
has the second best ever help and discoverability (after Matlab of course!)

~~~
legends2k
But. to do `help(thing)` you need to know what the _thing_ is.

With Python, many times I vaguely know something but dunno what it is exactly.
This cheatsheet solves that!

~~~
billfruit
Is there some way to list all modules available for importing? Some times you
don't know which modules are available to ask the help for it.

~~~
avip
>>> help('modules')

~~~
vram22
Related post on my blog:

Get names and types of a Python module's attributes:

[https://jugad2.blogspot.com/2016/10/get-names-and-types-
of-p...](https://jugad2.blogspot.com/2016/10/get-names-and-types-of-python-
modules.html)

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...](https://code.activestate.com/recipes/580705-get-names-and-types-of-all-
attributes-of-a-python-/?in=user-4173351)

------
fencepost
Seems to me that perhaps this should be a Show HN since it's submitted by the
creator.

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](https://github.com/gto76/python-cheatsheet)) displays just fine.

------
sametmax
Nice, but why does this needs JS to be rendered ?

~~~
pizzaburek
Because it's rendered directly from README.md. That way it's easier for me,
because I don't have to render it every time I make a change (I make a lot of
little edits all the time), and project's Github page
([https://github.com/gto76/python-cheatsheet](https://github.com/gto76/python-
cheatsheet)) always has the same content as webpage.

~~~
explainplease
It's quite annoying to have to enable JS for 3 different domains just to see
something other than a blank page. It also prevents non-JS browsers and
retrievers from seeing content.

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.

~~~
pizzaburek
Will look into it, thanks for info.

~~~
explainplease
Thanks for being open to the idea (unlike the downvoters). HN is so tiresome.

------
reacharavindh
Now, this I understand. I have to sit down and translate it to Rust :-)

------
udev
Something magical happens when you have a one page reference for a language or
tool. I just end up learning it much faster.

For me this is the best quick reference for Python (2.7 unfortunately):
[http://rgruet.free.fr/PQR27/PQR2.7.html](http://rgruet.free.fr/PQR27/PQR2.7.html)

------
plg
So to get a list of unique values you suggest I convert to a dictionary and
then convert back to a list? Is this the Python way? I dunno it seems like
acrobatics

    
    
      no_duplicates = list(dict.fromkeys(<list>))

~~~
occams_chainsaw
Easier:

    
    
      no_duplicates = set(<list>)

~~~
dagw
Except that won't return a list. You need list(set(<list>)). Also using set
means you lose list ordering, which isn't the case when using dict (assuming
python 3.6 or higher).

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>))

------
TBurette
I like the clean look and the overall way it is presented. The examples using
angle brackets (eg.: <list>.append(<el>) ) is highly legible and the one
column format is faster to scan.

~~~
Singletoned
I came here to say exactly the opposite. The angle brackets mean that every
single example is a syntax error.

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

~~~
wenc
I think the author of this document is trying to differentiate between types
(broad notions of course -- there's no type called 'num' in Python).

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...](https://docs.python.org/3/library/threading.html#threading.Thread)

~~~
Singletoned
But he could achieve exactly the same thing by using descriptive variable
names without the angle brackets. Admittedly he can't use `list` as it's a
built-in but `a_list` or `list_` would be much better than `<list>`.

~~~
pizzaburek
My personal opinion is that `list_` is among the worst possible variable names
(together with `bar` and `foo`). It's non-descriptive, ugly, hard to
recognize, looks scary to beginners and maybe worst of all it's easy to forget
the underscore when typing.

~~~
Singletoned
That's exactly what he's used, but with angle brackets around it. What do you
think he should have done instead.

------
vram22
In the section "Inline -> Comprehension", isn't this:

    
    
        <iter> = (i+5 for i in range(10))         # (5, 6, ..., 14)
    

really a generator expression?

~~~
pizzaburek
Yes, although there is a saying that "every generator is an iterator, but not
every iterator is a generator". But then again generator has a bunch of
methods (close, gi_frame, gi_yieldfrom, throw, gi_code, gi_running, send) that
iterators don't have... I really don't know if <iter> is correct enough here,
or should I use <genr> (that I don't use anywhere else and could be
confusing).

~~~
x3tm
I would've written:

<iter> = ( f(i) for i in <gen>)

where f() is some function of i.

------
v4ult
This is quite useful as I don't always remember syntax.

Are there any available for Ruby or Linux?

~~~
elmo2you
For Linux, from the same author: [https://gto76.github.io/linux-
cheatsheet/](https://gto76.github.io/linux-cheatsheet/)

------
nszceta
Empty set literal: {*()}

~~~
BerislavLopac
Considering it has the same number of characters as the idiomatic set(), its
only value is in curiosity as a special case of collection unpacking.

------
alexanderdmitri
I like your linux cheat sheet too. Thanks for sharing!

------
ngcc_hk
Is there a cheatsheet for cython to go with this ?

