top | item 19075325

Comprehensive Python Cheatsheet (2018)

335 points| pizzaburek | 7 years ago |gto76.github.io

81 comments

order
[+] gorb314|7 years ago|reply
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|7 years ago|reply
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.

[+] basil-rash|7 years ago|reply
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.
[+] omegote|7 years ago|reply
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|7 years ago|reply

   >>> list(dict.fromkeys([3, 2, 1]))
   [3, 2, 1]
   >>> list(set([3, 2, 1]))
   [1, 2, 3]
[+] tyingq|7 years ago|reply
They both choke on lists that contain lists.
[+] woadwarrior01|7 years ago|reply
list(dict.fromkeys(<list>)) preserves ordering, whilst list(set(<list>)) doesn't.
[+] dvfjsdhgfv|7 years ago|reply
Can we please change the current clickbait title (Best Python Cheatsheet Ever!) to the original one (Comprehensive Python Cheatsheet)?
[+] timdellinger|7 years ago|reply
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.
[+] avip|7 years ago|reply
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|7 years ago|reply
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!

[+] Waterluvian|7 years ago|reply
Yes! And implementing this help text for your library is free. It just assembles the docstrings found in your code. And then your favourite text editor can use this for autocomplete and such as well.

Treating docstrings as an actual reflectable part of a class/function and not just "comments to be ignored by a parser" is brilliant.

[+] nestorD|7 years ago|reply
I would put it after R help function and, even better, F1 key to get the full documentation of any thing in Rstudio.
[+] vageli|7 years ago|reply
I could not help but comment to add Elixir to the list of languages with amazing discoverability. For things in the standard library, you essentially get a condensed version of Python web documentation, with examples!
[+] legends2k|7 years ago|reply
What 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!

[+] fencepost|7 years ago|reply
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) displays just fine.

[+] sametmax|7 years ago|reply
Nice, but why does this needs JS to be rendered ?
[+] pizzaburek|7 years ago|reply
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) always has the same content as webpage.
[+] TBurette|7 years ago|reply
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|7 years ago|reply
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

[+] reacharavindh|7 years ago|reply
Now, this I understand. I have to sit down and translate it to Rust :-)
[+] udev|7 years ago|reply
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

[+] plg|7 years ago|reply
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>))
[+] nszceta|7 years ago|reply
Empty set literal: {*()}
[+] BerislavLopac|7 years ago|reply
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.
[+] ngcc_hk|7 years ago|reply
Is there a cheatsheet for cython to go with this ?
[+] vram22|7 years ago|reply
In the section "Inline -> Comprehension", isn't this:

    <iter> = (i+5 for i in range(10))         # (5, 6, ..., 14)
really a generator expression?
[+] pizzaburek|7 years ago|reply
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).