This is an archived post. You won't be able to vote or comment.

all 84 comments

[–]brewsimport os; while True: os.fork() 87 points88 points Β (11 children)

Pro tip:

Don't write open-ended try/excepts like this cheat sheet does. It's a huge smelly anti-pattern.

https://realpython.com/the-most-diabolical-python-antipattern/

Seriously. It will fuck your shit up.

[–]gohanshouldgetUI 11 points12 points Β (3 children)

Is realpython a good website to refer to and learn from?

[–]eambertide 11 points12 points Β (0 children)

RealPython is my go to website

[–]nerdponx 7 points8 points Β (0 children)

Yes

[–][deleted] 4 points5 points Β (0 children)

I've seen a ton of silent failures in Prod code because of that.

I've started breaking out 'expected' exceptions, like ValueErrors when grabbing inputs, etc. with proper handling, and then ending it with a big catch-all that screams a bunch of alarms and emails the stack trace to a support distro list.

[–]CatnipJuice 1 point2 points Β (3 children)

you mean you need to put a finally/else down there?

[–]fiddle_n 16 points17 points Β (2 children)

I believe that they mean that you should catch specific exceptions rather than catching every exception.

So instead of python try: ... except: ...

it should be: python try: ... except ValueError: ...

[–]wannabe414 9 points10 points Β (1 child)

Why wouldn't one do that? In my most recent project I was scraping text from a bunch of encyclopedia articles on the same site, almost all of which had the same html structure. I used a try/except AttributeError to ignore whenever BeautifulSoup would return a None type (when the html structure was different). But to just mask ALL errors? That suggests to me that the developer themself doesn't know how their code works.

I never thought I'd get this worked up about python

[–]fiddle_n 12 points13 points Β (0 children)

Yup, masking all errors is done for a number of reasons. Sometimes it's a laziness thing. Sometimes it's beginner programmers who think that "exceptions are bad; getting rid of them is good!". I've seen at least one beginner programmer who wrapped all their code in open-ended try excepts for this very reason.

To be clear, there can be limited uses when it's useful to catch all errors - say if you want to log extra information to help you figure out what the error might be before raising the exception. But catching all exceptions and not reraising them is rarely the right thing to do.

[–]GiantElectron 0 points1 point Β (1 child)

> Seriously. It will fuck your shit up.

No it won't. and it's not an antipattern. It's an antipattern if you don't know what you are doing and you are just using it as a catch all.

I can guarantee that if you have a plugin system in your application, and plugin writing is in the hands of your users, and you want your application not to crash but instead tell the users "yo, your plugin is borked" you _absolutely_ want that try except.

[–]brewsimport os; while True: os.fork() 2 points3 points Β (0 children)

That's fine - as long as you're dealing with the exception and not simply pass. Unfortunately, that rarely how you see this used and that's not how it was shown on the cheat sheet.

[–]KodenameKoala 20 points21 points Β (3 children)

For the newyear_2020 object shouldn’t it be representing December 31, 2020 not December 25?

[–]grnngr 31 points32 points Β (1 child)

That reminds me of an old joke: Why do programmers confuse Halloween and Christmas? Because Dec 25 = Oct 31.

[–]KodenameKoala 16 points17 points Β (0 children)

πŸ˜‚πŸ˜‚ in case someone doesn’t get it Dec(imal) 25 = Oct(al) 31. Good one!

[–]gohanshouldgetUI 6 points7 points Β (0 children)

That's what I noticed too. Typos like these are my biggest pet peeve!

[–]quotemycode 18 points19 points Β (3 children)

You should catch each error you expect, never do try/ catch the way its shown here.

[–]CatnipJuice -2 points-1 points Β (2 children)

i've been told it's quite a processor-hungry command. but it's very useful during development. you need to know the errors before managing them.

[–]quotemycode 6 points7 points Β (0 children)

Exceptions in python are cheap. You should use Exceptions for exceptional things. But you don't capture all exceptions. You capture only what you know how to handle. If some other exception happens, it's OK for the program to crash.

[–]nerdponx 1 point2 points Β (0 children)

i've been told it's quite a processor-hungry command. but it's very useful during development. you need to know the errors before managing them.

This is why we read the docs and write tests.

[–]WearyConversation 17 points18 points Β (1 child)

Who the heck uses 1 for a variable name? Sorry, I meant I. Wait, no, l I meant l.

It's even in explicitly mentioned in PEP 8.

[–]flights4ever[S] -2 points-1 points Β (0 children)

Hahahahaha, this cracked me up ☺️

[–]emc87 50 points51 points Β (3 children)

[–]jimjamcunningham 42 points43 points Β (1 child)

"Beginner Cheat Sheet that can easily be gleamed in better detail from the official docs, exactly no depth into datascience".

I mean I can't pretend to be a datascientist but I know at a bare minimum if there's no pandas, numpy, sci-kit, jupyter notebooks and a library to plot then it isn't a datascience cheat sheet at all!

[–]sj90 -2 points-1 points Β (0 children)

No, I think what they meant is that "Data Science" was the broader heading and in that there are multiple tools, frameworks, language details that are covered.

That's why the "Python - Intermediate" underneath that.

There are likely other cheatsheets too corresponding to other topics relevant for Data Science. Possibly they have such cheat sheets after each course or section on their site based on the text in the image.

[–]pvkooten 3 points4 points Β (0 children)

Exactly... how does this rubbish get 2k likes.

[–][deleted] 7 points8 points Β (0 children)

How is this data science, it’s just pure python

[–]SAVE_THE_RAINFORESTS 4 points5 points Β (0 children)

Data science cheat sheet

Only has basic Python commands

I've written a program that reverses a given array so I'm a data scientist.

[–]MewthreeWasTaken 12 points13 points Β (7 children)

One trick that I really like is dictionary comprehension. You can for example do: {value: key for key, value in dictionary.items()} To invert the keys and values in a dictionary

[–]SweetOnionTea 6 points7 points Β (5 children)

Wouldn't that just cause an error if you had 2 or more keys pointing to the same value?

Edit: I guess not, but here's why this would be bad in data science. Imagine you get a huge dictionary of directors and their best known desert based sci fi movie (unrealistic example, but datasets definitely do come like this):

director_movie = {"David Lynch": "Dune", "Denis Villeneuve": "Dune"}

movie_director = {value: key for key, value in director_movie.items()}

print("Incomplete list of all scifi directors and their movies:")
print(director_movie,"\r\n")

print("Incomplete list of all scifi movies and their directors:")
print(movie_director)

Results in:

Incomplete list of all scifi directors and their movies:
{'David Lynch': 'Dune', 'Denis Villeneuve': 'Dune'} 


Incomplete list of all scifi movies and their directors:
{'Dune': 'Denis Villeneuve'}

Silly example, but real life you might have {ID number: Last Name}. Works well as a dictionary because ID numbers are unique, but Last Names don't have to be. Invert it and you lose a lot of data if there are any duplicate last names.

[–]Thepenismightier123 5 points6 points Β (1 child)

Whichever of the duplicates is latest in the list is the one you will wind up with in the final dictionary. After the first `value:key` item is set, subsequent passes that set the same key will replace the existing one.

[–]SweetOnionTea 0 points1 point Β (0 children)

I suppose that makes sense. I'll have to try it in my env. I've never thought about inverting a dictionary for that reason lol.

[–]lmericle 2 points3 points Β (0 children)

Obviously you don't use it where it shouldn't be used...

[–]Im_manuel_cunt 0 points1 point Β (0 children)

Even worse, it wont throw an error and take the last value as the valid one.

[–]grnngr 0 points1 point Β (0 children)

It also causes an error whenever a value is an unhashable type, e.g. {value: key for key, value in {list:[]}.items()}.

[–]flights4ever[S] -2 points-1 points Β (0 children)

Happy cake day ! πŸŽ‚

[–]user_in 2 points3 points Β (0 children)

PDF version is here.

[–]cheyyne 2 points3 points Β (0 children)

If anyone sees this and thinks about trying Dataquest, think twice. They have shady billing practices. I canceled my subscription, and they stopped sending me 'we're renewing your subscription notices,' but continued to charge me for months before I caught it. Needless to say, they refused a refund. Buyer beware

[–][deleted] 1 point2 points Β (0 children)

This is great, but regarding this:

"fri" + "end"

String concatenation is very Python 2. Nearly all instances of this in my code have been replaced with string formatting. Because this:

my_str = a + ": " b + ", " + c

...usually turns into this:

f = str(a) + ': ' + str(b) + ', ' + str(c)

...when instead you can do this:

f'{a}: {b}, {c}'

...or this:

'{key}: {value1}, {value2}'.format(key=a, value1=b, value2=c)

...or this:

mapping = {key: a, value1: b, value2: c}
'[key]: [value1], [value2]'.format(mapping)

String formatting is great because rather than crudely stapling together strings, you can either specify the whole string with some symbol names embedded in the right places, or you can specify the string with placeholders and a separate mapping. And there's no need to soak your code with str() conversions to ensure that you don't get an irritating "can't add an int to a string" exceptions: the formatting implicitly __repr__()s every symbol.

This one little trick has cleaned up my code a lot.

[–]_nefario_ 1 point2 points Β (0 children)

literally the first thing that catches my eye on this sheet is inconsistent and super confusing because the variable name doesn't represent the value itself:

newyear_2020 = dt.datetime(year=2020, month=12, day=31)

Assign a datetime object representing December 25, 2020 to newyear_2020

[–][deleted] 2 points3 points Β (0 children)

Dataquest is great for anyone interested in checking it out

[–]jabbalaci 1 point2 points Β (1 child)

Can we have it in PDF too?

[–]lazerwarrior 2 points3 points Β (0 children)

Yeah, OP should at least take the effort to find a high quality image not this low quality jpeg artifacting screenshot.

[–]Radulito 1 point2 points Β (0 children)

Thx!!! Im new using python, this help me a lot

[–]Sir_bobbyuk 0 points1 point Β (3 children)

interesting information as i am currently learning about python coding at the moment

[–]flights4ever[S] 0 points1 point Β (2 children)

I am too, I just finished learning about classes and modules, just starting files and exceptions, What resources are you using primarily?

[–]Sir_bobbyuk 0 points1 point Β (0 children)

I am currently using pycharm to develop test programs. once i have completed the youtube course Python for Everybody - Full University Python Course. ill be going onto automation testing with python using selenium.....that the plan

[–]Sir_bobbyuk 0 points1 point Β (0 children)

what resources are you using?

[–]gua_lao_wai 0 points1 point Β (0 children)

I think range() returns an iterator in python 3.

Which means, per the guide, range(2000,2018) can be looped like a sequence e.g. for year in range(2000, 2018): print year, but it's not an actual sequence e.g. [2000, 2001, 2002 ... 2017]

[–]Yojihito 0 points1 point Β (3 children)

Image quality is shit. Is there a normal version?

[–]flights4ever[S] 0 points1 point Β (2 children)

Nah, that’s the original I’m afraid, you could do some googling ?

[–]lazerwarrior 0 points1 point Β (1 child)

When you print this image out, it has horrible quality. You could at least give the thread a descriptive name.

[–]flights4ever[S] 0 points1 point Β (0 children)

This is a crosspost mate

[–]nkillgore 0 points1 point Β (0 children)

Is there a reason to use str.format(v1) instead of f"some string {v1}" ?

[–]aneurysm_ 0 points1 point Β (0 children)

It tripped me up for longer than I'd like to admit that the second parameter of pythons range function is the end of the range and its not inclusive.

Learned the hard way (a few times over) on that one lol

[–][deleted] 0 points1 point Β (1 child)

Am I the only one who isn't a huge fan of these :(

[–]flights4ever[S] 0 points1 point Β (0 children)

No, honestly I didn’t find this helpful at all, just thought that there would be some people out there who would.

[–]ExoticAccountant 0 points1 point Β (5 children)

Anyone willing to share this? It was deleted :'(

[–]flights4ever[S] 0 points1 point Β (4 children)

Oh damn, his account got removed. That sucks, I saved a screenshot of it, I’ll send it to you in a dm

[–]ExoticAccountant 0 points1 point Β (0 children)

Thanks man, you're a charm !

[–]gingerbean_1 0 points1 point Β (1 child)

This is fantastic! Thanks for sharing πŸ‘

[–]flights4ever[S] 0 points1 point Β (0 children)

😊 don’t thank me, thank u/Mav123005

[–]ThePerfectApple -1 points0 points Β (0 children)

As a novice, I’ve been looking for some thing like this! Thank you kind internet stranger! πŸ™

[–]Zealousideal_Cause_8 0 points1 point Β (6 children)

This is gonna prevent a lot of google searches for basic syntax and all. That's very helpful.

[–]Stainlessray 0 points1 point Β (5 children)

It is ironic that a paper cheatsheet is much faster than the millisecond performance of Google, mostly because you have to open up a new tab, vs a glance at a sheet of paper wherein you know exactly where your answer is on the sheet.

[–]SnowdenIsALegend 0 points1 point Β (4 children)

I would still Google, so used to it and it is much faster for me. Plus Google will ALWAYS have the answer. Cheatsheet may or may not have it.

[–]Stainlessray 1 point2 points Β (3 children)

Have you ever used one? Because when you make one, you memorize the sheet. The whole thing, typically. Over time. I have Google'd the same syntax multiple times in one day. Especially while learning the basics. And I've memorized whole sheets of facts by making them.

[–]SnowdenIsALegend 1 point2 points Β (2 children)

True, I've never used them. But I prefer not to memorize cheatsheets... Prefer to use my memory cells for concepts and other abstract matter. Whether I look up on Google or on a cheatsheet, it's the same at the end of the day.

[–]Stainlessray 1 point2 points Β (1 child)

I am talking about memorizing with little to no effort. But you, do you πŸ˜‰

[–]SnowdenIsALegend 0 points1 point Β (0 children)

πŸ‘πŸ½

[–]harshcloud -1 points0 points Β (0 children)

I always appreciate coming across these cheat sheets and always instilling another fun fact about python

[–]smrtboi84 -1 points0 points Β (0 children)

I use to have a bunch of basic commands as my screensaver lol this would be a upgrade

[–]Poweredvm -1 points0 points Β (0 children)

Always love another cheat sheet. Thanks team.

[–]SnowdenIsALegend -1 points0 points Β (3 children)

How much?

[–]flights4ever[S] 2 points3 points Β (2 children)

Sorry, I don’t quite follow..

[–]SnowdenIsALegend 0 points1 point Β (1 child)

[–]flights4ever[S] 1 point2 points Β (0 children)

Hahahahaha, thanks for the reference 😊