Raymond Hettinger - Beyond PEP 8 -- Best practices for beautiful intelligible code - PyCon 2015

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments

Just chiming in to say this guy is flipping awesome.

There's like 4 or 5 of his talks on youtube. If you're like me, you walk away from each one thinking damn, he answered so many questions I didn't even know I had. Answers that turn you into being a better, more pythonic, python programmer. As far as I can tell, his talks are uniquely targeted at all skill levels beginner, intermediate, advanced.

tldr Can't wait to watch this.

πŸ‘οΈŽ︎ 64 πŸ‘€οΈŽ︎ u/bionikspoon πŸ“…οΈŽ︎ Apr 12 2015 πŸ—«︎ replies

SPOILER WARNING: Man, when he showed the code cleanup example starting at 12:37, I immediately noticed the try: finally: and thought, "hmm, looks like we could use a 'with' here". Then the PEP8-ifying began and it distracted me so much that I completely forgot about the 'with'. Great example.

πŸ‘οΈŽ︎ 22 πŸ‘€οΈŽ︎ u/dunkler_wanderer πŸ“…οΈŽ︎ Apr 13 2015 πŸ—«︎ replies

Best thing about PyCons: the Raymond Hettinger's videos.

πŸ‘οΈŽ︎ 12 πŸ‘€οΈŽ︎ u/[deleted] πŸ“…οΈŽ︎ Apr 13 2015 πŸ—«︎ replies

Can confirm. Saw it in person - awesome talk!

πŸ‘οΈŽ︎ 20 πŸ‘€οΈŽ︎ u/forbidden_doughnut πŸ“…οΈŽ︎ Apr 12 2015 πŸ—«︎ replies

Can someone explain what the "val" discussion was at 48:50?

πŸ‘οΈŽ︎ 12 πŸ‘€οΈŽ︎ u/AnythingApplied πŸ“…οΈŽ︎ Apr 12 2015 πŸ—«︎ replies

His point about writing classes with proper destructors so you allow callers to use with() was rad. This applies to tons of code I write.

πŸ‘οΈŽ︎ 7 πŸ‘€οΈŽ︎ u/TR-BetaFlash πŸ“…οΈŽ︎ Apr 13 2015 πŸ—«︎ replies

I've been writing Python code for years and never knew about @property to avoid having to write getters and setters.

Now instead of

class Computer(object):
    get_ip_address(self):
        . . .

I can do

class Computer(object):
    @property
    ip_address(self):
        . . .

And users of my class can simply do

print comp.ip_address

Rather than

print comp.get_ip_address()

But what happens when a user assigns to ip_address?

πŸ‘οΈŽ︎ 13 πŸ‘€οΈŽ︎ u/goodDayM πŸ“…οΈŽ︎ Apr 13 2015 πŸ—«︎ replies

great as always!

πŸ‘οΈŽ︎ 5 πŸ‘€οΈŽ︎ u/teacpde πŸ“…οΈŽ︎ Apr 13 2015 πŸ—«︎ replies

He is a very good speaker I watch all his talks and learned alot from them.

πŸ‘οΈŽ︎ 6 πŸ‘€οΈŽ︎ u/chchan πŸ“…οΈŽ︎ Apr 13 2015 πŸ—«︎ replies
Captions
or early afternoon so let's get ready for the last talk of this session this is Raymond Raymond Hettinger telling us about beyond pep 8 how to write best practices for beautiful intelligible code I was not sure it was possible to go beyond pep 8 in beauty so we're going to find out how and yeah so here he is oh my goodness there's a lot of you I actually didn't think anybody would come I'm going up against Benjamin Peterson who's in the other room so I can presume his room is overflowing and that's why you're all here how many of you've read Pepe how many of you liked Pepe who doesn't like Pepe why not that's the part I don't like either the line with Bart it bugs me why does the line with part Barbie you have to wrap your comments in 72 characters you have to terminate your lines in 79 characters when does it bug me one time it bugs me is when I'm writing unit tests when I'm writing unit tests I have to start with the class and then inside the class there's a def for tests and then the test starts out with a self assert equal and by then most of my line is gone so by the time I get to any business logic and my test I'm near the end of the line but what happens if I go over 79 characters what if I hit eight what if I hit 81 what bad thing will happen something does bad does happen what is it that is not the negative consequence I have never seen a little puppy die ever because we hit 80 characters but something dad does happen there's a reason I fear it as I start to get up around 78 characters and I know I've got a few left I get worried why I lose my breathability at 82 characters I don't buy that no no there's something I worried about something bad I know it's going to happen Larry Hastings five bucks say your answer again sir somebody is going to come pep ate me they're going to let my coat have it your code is non-compliant maybe they'll have an import hook so I can't get my code checked in maybe after it's in they'll come in and say oh Raymond's carry a line hit 81 characters I'll pep ate it and so while I'm not looking they come in and reformat my code so how do they get it to be back under 79 characters they get office gating now they'll just throw in a line break at some really awkward point does that make the code better it doesn't so I feel the fear as it starts to come up this is not a good thing how do I deal with my fear because I wouldn't want to face this terrible ending what do you do I'm feeling some pressure and that pressure has nothing to do with writing high quality code it has to do a vow with avoiding somebody who wants to come pepΓ© defy you so what do you do you realize maybe I can just commit a little atrocity and that way no one will ever come paid me so as I start to get up my light starts get along I like I can save myself some line wrapping if I just shorten my variable names there now it fits into 75 characters and then whenever we'll pet bait me is my code better or worse worse my recommendation for the line length ending outside the standard library when you can set your own policies is 90 ish I picked 90 because 79 tends to be a little tight in Python if you're using for space and Den's my understanding is at Google they had a little war over this because at Google they tend to have many levels of indentation and if you've ended several levels deep and you're already close to your line limit there's not a lot of room for code so what did they do about it I don't know this for sure I just had it on rumor their solution was I know will indent less to space and dense does that make the code better no but it fits in seventy-nine characters they would rather fit in seventy-nine characters and give up the intelligibility of that that comes from for space indents even a big organizations can succumb to the temptation to have an atrocity just to deal with those nigh on line endings so I see 90 in part so that you can use for space and Den's but I don't say 90 exactly I say 90 ish the ish is important when you're doing your own version of Pepe for your own team what you want is as a person's line starts to get long for the to start to feel a little anxiety to say maybe I should be splitting my line maybe I'm doing too much in one place use it as a hint that they're not doing something great but if they start to stroll up near your ending and they're going to be a couple characters over you'd rather have them go a couple characters over then commit an atrocity so I put the ish on there as your line gets longest you might want to think about whether you want to chop it into pieces because not only is it visually hard to read but you're probably putting too many thoughts on one line how many of you agree oh this is fantastic no Pepe zealots in the room I mostly love Pepe I think it's extremely well-written I also think that right at the top where it says foolish consistency is the hobgoblin of little minds people skip right past that part and guess where the little minds go right very quickly is to Pepe now I'd like to pick on these people as if they're not very bright but don't freeze it another way I've had a job at a cloud computing company once where I was hired in for my Python skills people are expecting me to be really good and then I was asked to do a lot of things that didn't involve Python skills that I wasn't particularly good at and I felt a lot of pressure people were paying me a lot of money there were expectations for astonishingly good things to come out and I didn't know exactly what to do at some point your career you will feel this sort of pressure what do you psychologically what do you really really want to do you very much want to deliver something that your employer the people who are working around you were going to like something that you can check off and said I did something productive today that everybody thinks is cool so suppose there's some low-hanging fruit something that you can see that you just say I know how to do that do you think there's a strong psychological temptation to jump for that I know there is because I've felt it on a lot of teams sooner or later you get a coding problems that are hard people have varying levels of skill and some people jump right in and seem to know what they're doing and others struggle a little bit that's natural what you want them is the people who are struggling a little bit to overcome and deal with the problem and at some point become very effective how can you prevent that get outcome it's easy you give them some low-hanging fruit something to go do that seems productive but is it and one of those things is a certain pep located between 7 & 9 I've done a lot of consulting work I do a lot of code reviews for a lot of companies I do architectural reviews I help teams organize and here's something I've seen over and over again the person on the team who is struggling the most and they might actually be bright but they are faced with problems where they don't immediately know what to do will gravitate to Pepe like a moth to a flame they will reach in to your codebase and Pepe to five stuff and they can check off every day what have you done I baited all of these modules did it make the codebase better well it might make it a visually a little bit prettier but it doesn't necessarily make it better and in fact the people who wrote the code to begin with come back and find their code a little bit scrambled and when you start to use an SP in blame or HG blame or get blame you go back and you find the name not of the person who made the code but of the person who made all of the minor formatting changes and it starts to wreck your code history but worse we get a lot of op f8 submissions to the bug tracker in Python people want to contribute to the core in some way the problem is the core has been around 25 years and lots of the easy things to be done have already been done so what's the easiest way for you to contribute to the core if most of the stuff in it is done very nicely you could go through and Pepe to find it and so you step into code that I've been maintaining for the last 15 years and you start to rearrange it and so we get patches along those lines and one thing I've discovered is that when these patches come in a person is trying to make the code better making it Pepe compliant which is not necessarily a bad thing but an amazing number of times it introduces bugs into the code and so I want to caution you about that so that's those are the downsides of Pepe I'll just get out of the way what my worries are about it right now worry number one is that you end up with code that's beautiful but bad we'll take a look at that shortly number two you'll have a distraction from code quality see what's up on the screen here this is a rather famous psychological experiment what you're supposed to do is quickly look over these colors and name the colors not the word but the color so for the very first one you're supposed to say green for the second one you're supposed to say red for the next one you're supposed to say blue and most people find it hard to do because the word overpowers it and when you start to put Pepe in the forefront of your mind what happens very much like this experiment it causes you to reach for something that doesn't improve quote quality and an important way could that ever happen to you it wouldn't happen to you you're an experienced developer what happened to you now you would never put a form over substance it happens all the time it happens when we shift our focus I had some idea of playing this little video here in the background while I go along this one is also famous but I don't want to belabor the point and what actually get into code very quickly so this is famous I think it copyright 1999 these people are playing basketball what you're supposed to do is follow the people in the white shirts and count the number of times they pass try this for a moment count the number of passes okay and now handful of people are laughing or seeing what you're actually supposed to see a gorilla just walk through the middle of the scene if you were actually counting passes most people by when I say most 99 out of 100 will count like passes almost correctly and not ever see the gorillas so if you get yourself in a Pepe ting mode what do you tend to see now okay this uh this highlights it quite a bit you tend to see the Pepe stuff and not what really matters now I'm going to do the dangerous part of my presentation this year I'm speaking with no slides this year I'm speaking with Emacs wish me luck we're going to confront a famous problem in computer science P versus NP you guys all know about the P versus NP problem I face it every day because what do I do for a living I train people I do code reviews I do architectural reviews I help teeth teams organize and I face P versus NP every day how many of you think P versus NP is a problem in computational complexity oh then you don't know what this one's about this is about pythonic versus non pythonic yeah gotcha and what am I about to do I'm about to not get glib anymore instead I'm going to show you what I do for a living I'm going to give away some of my bag of tricks hopefully you can reproduce this most of the things I'm going to show you are taking out a real code from client code I've changed some of the names a little bit to protect the guilty and in a lot of the cases these developers who made this code are good and these are very smart people so we've got some code here fairly short and what does it do well we've got a series of imports from an SDK that knows how to talk to a routing device okay it makes a connection to the device gets the routing table but if the routing tables missing it require logs an exception and it doesn't clean up this particular connection if you don't clean up on the our way out can leave the router in a state that's hard to log back into so there's some nice handling here in addition it determines the size of the routing table looks at loops over all of the routing offsets for each offset it finds the appropriate route then it calls the method to get the routes name then it gets the IP address and then after that it prints out a short little report of all of the names of the route and their IP addresses and then at the end it got commits any changes cleans up and disconnects fairly just a straightforward little script very close to what I have seen in real life any questions about what it does I didn't think so because that's not the point of it is this code beautiful no it's beautiful better than ugly yes do we have a pip to tell us how to make this better should we make it better yes and should we get a code review and have somebody look at it sure someone headed off to the big boss the boss looks it over and says hey you know this Moss has been taught a little bit about positive leadership nice error recovery and logging there Raymond I really saw I saw a script one time that didn't log out the errors and didn't do any recovery that was a great job you should clean up the code formatting this a little rough of my eyes did oh by the way after you've polished it up a little bit should we use this as a template so that we can make lots of other scripts just like this which is a reasonable question gee thanks the boss how do you like the positive leadership there little nudge to clean up the code but basically good job and I'd like to lose your code as a model so I'm going to go clean it up let's see this is a P versus NP to dot dy by the way I'll give you all this code but it's the code is not necessarily the point what would Pepe say about these imports why not just put them on separate lines in fact a lot of people go as far as alphabetizing their imports that is actually important if you have dozens of imports if you have three or four or five alphabetizing them is a kind of a waste of a time doesn't it already look better okay one of the things that uh Pepe will tell us is to put a space and let us I either side of the equal sign keep in mind these conventions vary from language to language in some languages you don't tend to put spaces on the outside of equal sign in some languages it is very common to put space around the upper entha cease to Python people this looks weird the spacing here looks a little strange so what I'm going to do is put in a get my network element and then go ahead and tighten up the try/except and else the job it doesn't have odd spacing inside feb 8 2015 3 better off without it now we know we have an exception when we tried to get the routing table so you already know it's a table fault if you're logging it you already know that you're recording it now this gratuitous switching of quote characters people used to really love double quotes I don't know why oh it's because they were coding in C and then switching over to Python single quotes are easy to type you should basically model after what the reppers and the python do that represents our best practice that said double quotes are making a comeback why because people are starting to type JSON directly into their code and you start typing a little JSON suddenly everything starts to look like Jace all by the way say it with a long o J song which is kind of cool J son is a person which a song it's a file format alright so I'll clean this up with rollback which is part of the API it's a code already starting to look a little better on the eyes it will be pep 8 compliant momentarily possibly I'll introduce some typos along the way which is a fact a risk of Pepe ting and we'll put some spaces in here and evaluate the code quality and I think you're going to find it to be dramatically more readable just remember there's a lot of things about pep 8 I like I don't dig the line endings don't get me wrong but everything else mostly is little space hereafter inside the tupple like a common space just like you would do in English and I think commit says lock-in changes pretty well and now you have code that I think looks pretty darn good is it was it worthwhile for me to pepe defy this code who should do it the intern the most senior person on this team the author that's the golden rule of Pepe Pepe done to thyself not unto others Pepe tis not a weapon for beating other people in the head it's a style guide a guide not a law book and if you read Pepe and internalize it you will tend to make more beautiful code but if you treat it as a law book it will come to ruin your life also there was some weird indentation in here and inconsistent Python allows that but now that everything lines up in line better I think the logic of this is more transparent how many of you like this code a lot better how many of you would let me check it in oh well I have you haven't seen the unit test on it okay there's unit tests and Docs now how would you let me check it in okay good and this code is not hard it is straightforward python is a remarkably good language in terms of communicating ideas and I think it is a it leads to fairly clean code you guys didn't see the gorilla did you what's that oh yeah the indentations a little off on the for-loop that'll make it better you guys are still counting passes not a single one of you is seeing the gorilla in the room what's up I'm giving away my bag of tricks I'm going to show you what I do for a living when I go to help out teams I got to start to look through their code and I don't want to fix their broken code I teach them about unit testing and I presume that they know their field of expertise well what is very common though is people write code like this one because it's an obvious thing to do number two it's an incremental style of development you at you get the routing table then you see an exception and you go and add something in but there's a part of the people playing out that people miss and it's very easy to miss because there's a problem here that seems at first like it's beyond your control this API came from Java and I don't mean Java asked in a pejorative sort of way in fact there was an API for this SDK written in Java and an automated conversion tool converted the Java bindings to Python bindings so that people could write this Python code which is why although the naming conventions here look Java esque they get routing a table it's why the code reads like Java and Java properly written looks very close to this and Java is a pretty decent language but none of you've ever been dating my talks before what you're supposed to say right right now ready ah who was that there you go there must be a better way here you guys ready ready there is a better way far better way let's try this with open no I should probably do a from net tools import network element with Network I'll cheat doing live coding is incredibly dangerous how many of you make sound effects when you type as in e for route in any routing table gee oh yeah we missed that in our Pepe ting up here p.m. spacing is very important around operators that's essential for code quality this code does the same thing which code is better the code on the top of the bottle one of my big problems with Pepe is not the pep itself it's extremely well written the ideas in it are good it's stuff you should do one of my issues with it is the effect on the human mind and when you get people to focus on Pepe what they do is count the number of basketball passes they read the name of the color instead of looking at the color and they don't address that P versus NP problem pythonic versus python on on python a the code at the top is non pythonic the code at the bottom is pythonic there's only one problem the code at the bottom doesn't run it won't work but other than that is really good code why won't it work because the entire API was developed in Java the rapine found bindings for it that require you do your imports like this do we have packages up here dot this dot that packages not a honking good idea when do we you need packages you need packages when you have an enormous amount of code with potential name place namespace conflicts between the area of the various parts if your code is not enormous for the most part you don't need the dots in packages at all that is becoming widely overused in Python it was appropriately used in the XML libraries because we have several XML libraries where they're conflicting package name our module names if you don't have that all you're doing is making your imports harder on the user and in fact in the real example where this code was derived from there were about 20 lines of imports and all of them had dot this dot that this is actually nicer than that code so the code at the bottom is profoundly better it's pythonic way better what all is going wrong here one is every time you connect to one of these devices you're going to need to do cleanups or rollbacks that should be factored out well-written Python code looks like business logic my question is how do we transform the API itself so that we can write this sort of thing I'm going to teach you to prefer a number of things when they're recurring set up and try to a teardown logic you should build a context manager so that you can use a with statement with this where there are packages you should make a single module that makes it easier to import everything so that the code can now become beautiful where somebody is getting the number of elements looping over a range and looking up and something by index there's a couple things that should change there's a name for this in Python is the Lin function so you should define a dunder tool in there's a way in Python to get something by index it's called square brackets and it's very readable and beautiful there's so you should actually know if you have method names like this is a hint that you're doing it wrong you're coming from a line you're bringing in your experience from a language that doesn't have these capabilities but in Python anything where you can look something up by index that raises index error when you go too far and that you could do a length on is known as a sequence strings or sequences Unicode is our sequences list for sequences tuples or sequences decks or sequences are there a lot of these things in Python yes and they all have one thing in common they're iterable which means you shouldn't loop over stuff like this or you shouldn't have to you just loop directly over it up here we did a get routing table I'd like to teach you a very strong preference for properties in your api getters and setters or what you do in languages where you don't have descriptors you have to do it in those languages if you design classes in Java and in C++ and you don't make getters for your attribute you're incompetent you're creating code that is going to be very difficult to maintain if people start using that API and you have to change access to the attribute you won't be able to so that is a strong rule in those languages does it apply in Python we don't make getters and setters why not because we can put properties in after the fact if we need to a getter and setter is a hint that you're doing it wrong in a Python so the more pythonic way is dot routing table likewise getname is replaced with dot name and even if these actually do have underlying API calls and even they aren't attributes we make them look like attributes through properties the second piece of code is a lot easier to write its main easy to maintain and it's easy to make a lot of variants of it remember the big boss asked us can we use this as a template so we can make lots of other code just like this the one on the bottom yes the one on the top will cause problems in your organization and that's what I mean by beyond Pepe beyond Pepe is paying attention to the things that really matter using the language features using the square brackets using the Len function using the magic methods using the context managers using properties and not coding like your Java programmer because in some ways there is nothing wrong with this code it works and it's readable on the other hand I think you can agree with me that they code on the bottom is profoundly better how many of you agree sweet all right P versus NP mp3 though that's the result P versus NP for how did I achieve all of this never do live demos it's certainly not with Emacs what could possibly go wrong P versus NP Oh so their school for we need small our type size their line links don't matter as long as you can shrink your type size what is pythonic the P problem it means coding beautifully in harmony with the language to get the maximum benefits from other language what is our goal here our goal is something I hope I've just given you a deep lesson for how to recognize non ponic pythonic AP is once we Pepe did that code it would pass most people's uh coding standards it would get checked in and it would live for a long time and other people would copy that style and we would all congratulate ourselves we're being Pepe compliant and there's nothing wrong with being Pepe compliant what is our all wrong is ignoring the gorilla which is uh what is pythonic if you accomplish being able to recognize law non pythonic code then this was worth a trip up to Canada so what do you do if you're given an API that's terrible there's a pattern for it there's an entire design pattern for it it's known as the adapter pattern we'll write an adapter class what should we do we should avoid unnecessary packaging in favor of simpler imports if your users are having to type dots all the time when they import things you're doing it wrong there very few needs for dots and packages in the world they do come up occasionally those were introduced to solve a very particular problem but now everybody and his brother is making a package every time they write even the smallest amount of code and that's an atrocity another thing you should do is create custom exceptions in your application custom exceptions could let you give a name to a problem that's very clear that tells a person what the error is we've already mentioned using properties instead of getter methods creating context managers and using magic methods in a retro for debug ability actually I didn't mention the wrapper before but get in the habit of putting reppers on your classes it makes debugging so much easier when you have something beautiful to look at so what did I do at the top here I started with the API as given the JSON tools element are jaynette tool network element but then I built my own exception not hard to do it's a one-liner in Python now I create a new class a network element not the original Network element but my new one and what it's going to do is wrap the underlying object so when we create it from an IP address what it does is call out go out and call the original code and saves it as the old network element in other words that what the adapter does is take the bad API and give you an adapter to the good API so think of our power adapter when I go to the UK they have these big honkin plugs I thought it was kind of crazy why they have why would you have huge blogs Americans don't need them and then I went to make some tea oh the pots of water boil twice as fast it's not just 220 volts 220 volts at 15 amps you can boil a kettle of tea like that then I started to appreciate it what did I need to Jack in my computer though I needed an adapter I needed to take my American API plug it in to the UK API that's what we're doing here this part is the UK API and this part is going to be our API and essentially what we did here was when there was an exception we pushed it down into our API ideally you don't want all of your business logic to be cluttered with error handling logic for the most part in Python exceptions lets you push that logic down wrap that sort of stuff so that in the end your business logic is clear and floats to the top so I'm putting it inside the lookup of the routing table rather than outside and when I catch the exception missing ver which is uninformative I replace it with an informative exception a great reason to wrap is to replace crummy error messages with good error messages that's a good message and a good exception name but also I put a property on it and why over on the right we can do routing table the other thing I did was put a context manager in it the gender enter and enter exit over here on the right there is setup logic every time you connect to this network element you're going to have to potentially if there's an exception log the exception and clean up if they're on the other hand you will don't want to do a commit and a disconnect over here I put that logic in the exit and the exit says hey if we had a network element error let's log it out and roll back all the work otherwise let's go ahead and do a commit and then disconnect by factoring this out every time I use this network element I can use width and all of that setup and teardown logic has been done exactly one time for me the code is far clearer on the right if we push this logic down a little bit the rubber will make this thing easy to debug okay this is good technique don't hardwire the name of the class network element every class knows its own name well we already know in advance the name is network element why would I parameterize this what's the advantage Larry subclassing because if you subclass the name of the class changes and you want your subclass or to be able to use your repre the network element is now much better we call it with the IP address it returns a network element it does the inter exit it looks pretty and we can do a dot routing table on it notice I didn't actually do any business logic inside this adapter code all I did is transform bad API to good API it's like the adapter from my power paw socket it doesn't change the amount of power going through it just changes one kind of socket to another all the entire amount of work done in an adapter class is transforming one API to another it doesn't actually do the work now the routing table itself what did we do for it well we used to call have a method called get size what do we call it now this part bigger their mercy for the people in the back row very little mercy but some okay so all we did essentially was renamed the method when you sail in in Python it means how big is something that's a lot better than a method get' sighs and when people said get route by index what's a better name for that in Python and what exception do they expect if they've gone too far all we're doing is changing in p2p non python it to pythonic next one up Oh once it has a good item in length what is it called in Python a sequence and all sequences are iterable which that means now I can do a for loop on it even without calling the LAN or the get item directly we learned something new no one knew all of you knew that already okay just check in how much work would this is this looks like a big block of code I built this adapter class in under 10 minutes I might have done five I'm just a conservatively remembering look how long it takes to make the routing table where there's a get sized make a loan where there's a good item are get by index make a indicate item and put an index error and it's automatically iterable this is one two three four lines of code in order to transform the API it's so easy to do that if you don't transform bad api's into pythonic api's you're a fool and I'm serious about it that is one of the number one things I difficult I go and they say we've got 50,000 lines of stinkin go not like well we could make it into 10,000 lines of stinking code and then go in for a bit there's some adapter classes sometimes the ideas in it are good but they are lost over here in this big wall of code it's hard to see the business logic as opposed to on the bottom right we could see all that and then finally on the class route very simple adaptation where there was a get name we put a property and that's the Python way I'm leaving you with this file I'm going to give I'm not going to publish a set of slides but I am going to make a little web so for this which shows all of my code examples here and which the way you're supposed to review this is go click on P versus NP for and right at the top is a little dot string that says Raymond's recipe for baking code better most of you can go back and apply this right away and start using the properties in the context managers and clean up your setup and teardown logic and transform code from the top code to the bottom okay are you guys enjoying the talk so far and Emax has not disappointed me yet I'll risk it I'll do more live coding we will go miscellaneous one several things I want to demonstrate here top one is a function call function call uses a positional arguments I think it's fairly obvious what this does this calls a function of four arguments the first argument is a string the second is a number and it's got two boolean x' my bet is that on your very first day of learning Python you knew enough to understand this good how many of you are clear that this makes a function call before arguments a string a number and odd to billions programming languages don't get it any simpler than that simple beautiful code and do you notice the space after the comma is Pepe compliant I didn't use triple quotes here no backslash eanes Pepe is that code awesome what's wrong with it you don't know what it does why not all you have to do is look up the API I know when I wrote the function P f TS I knew exactly what it did when I wrote it does that improve your understanding a little bit python is a beautiful and readable language but only if you meet it halfway we can't make you write good function names and our good variable names is the code nail profoundly better yes in all languages should you use good variable names are you sure does the need vary from language to language in fact it does and see I make a type declaration a file pointer F then I call a function with F in it itself a good variable name it's a perfectly decent variable name because I had a type declaration that said it's a file pointer and that was right beside where I made the call in other words you have more information than the variable name you have the declaration in Python do we have type declarations no so should you be a lot better about your variable names to make up for the loss of information yes in different languages we code to their strengths and weaknesses where there's the redundant CNC from the type declaration you can make your variable names oh you don't need to add as much information in the variable name because you've got additional information in the type declaration enough said python creates a need for better names what topic do you think I'm searching for on Twitter that is an incorrect hypothesis what topic do you think I'm searching for Obama okay so I have some people who have some personality issues these are the people who like to work against your team just so you know kind of me like things we're going too smoothly at the office I'll put some speed bumps in now they're people with a good sense of humor and Python fortunately attracts those because remember pythons net name for a mean carnivorous snake its name for a British comedy troupe so if you laugh and have a little fun while you're doing it you're doing it right so I think most people could guess that they are very accurately that the topic we're searching for is Obama what is less clear is what the other arguments mean Python you don't have to use keyword arguments most of the time but you should and you put them in anywhere where somebody might miss read this so this code becomes profoundly better if I say the number of tweets is 20 the number of retweets is false are that I want don't want retweet someone original tweets and Unicode I would like to allow that so I could find out what they're saying about Obama and other languages is this code profoundly better that one of the simplest things you can do to improve the quality of your code is to use keyword arguments anywhere the names aren't simple remember the code was Pepe compliant before but it's better now good function names matter all right here's some fairly straightforward Pepe compliant to code we've got a simple tupple you guys know about tuples a mutable or immutable immutable what's the length of this double three how do I extract the 170 be square bracket zero how do I get the point one can I unpack a couple so you guys all understand tuples okay so you understand this and this very square root of x lon it's going to look up which number 0.1 is 0.1 bigger or smaller than 0.5 smaller so is it going to say that's bright okay how about this one well oh well this if Clause trigger printing wow that is light so one hundred percent of you in here understand this code every single person accurately predicted what it's going to do and it's Peppe compliant it also sucks because you guys can't answer a fairly important question well I actually think you can't answer but I can be wrong in this audience there might actually be a handful of people who know would you wear this tubble there's somebody who might actually know I know that some Python needs to serve photographers that's exactly it five bucks somebody figured it out isn't it great when you write code that's Pepe compliant and out of a room of 500 people one person can figure it out that's a goal to strive for I know what you're thinking I'm doing this live on stage for a reason one of the reasons is I want you to have been very conscious how long it took me to do it it's at 10 to 15 seconds not done in the the calm of the green room but with lots of people watching over your shoulder ready to make a cat call the moment you make a typo somebody say some Emacs meanie saying well you should have just used ctrl alt Q X exclamation point with your left pinky and that would have done it it takes so little time it is so easy to do if you don't do this you're a fool the code is profoundly better the repper for this will say this is a color whose Hugh is on 170 on the color wheel under 70 degrees lightly saturated highly luminous is that tinted color and photographer terms the code is now profoundly better this is one of the easiest ways to clean up your code when you're done with this talk first thing you should do go eat second think you should do go back and look at your own codebase and say do I have a bunch of tuples floating around that aren't self documenting if so fix it it's only a couple lines of code make a name couple pain tuples or your friend who made name tuples oh I did do you like them who in here doesn't like name tuples one person that's because you looked at the source code and you saw that I used a Val and it makes you mad doesn't it even though I chose it for our sound business reasons like now everybody can understand the code I never get a question on how name tuples work because they're a self documenting it's also very easy to maintain and you can print out the template so you don't have to use a Val at all and you can cut it out go run it through pipe I run it through scythe on and get an optimized name double it has a huge number of advantages but a Val makes you mad doesn't it sir you know cuido used eval when he made a time until he should go let him have it during lunch you know if that Raymond is using eval and cuido soon as a valve that is two hints that you're doing it wrong okay fair enough I hope you guys like a name couple and a balance one of those things you want to be cautious with because it's very easy to introduce security risk with it on the other hand if you are cautious with it you can introduce great simplifications to your code and so you shouldn't chop off your left arm right arm one of your legs and your other leg while trying to prevent King author from crossing don't throw away a vowel it's one of your most powerful tools ok get quotes this is pep eight compliant code and it uses a dictionary comprehension what does it do it gets a bunch of quotes sir hi I'm sorry as we're kind of running out of time and we've got to get to lunch as you said we first thing we do is go and eat could we close this over and yes excellent do I still have time for Q&A or now no oh yeah he says can you be brief yes the thing that that bugs me here is args the RX represents stock symbols why does it matter NC it doesn't matter what variable name you use there because the parameters aren't exposed to the user but in this case in Python the parameter names are exposed to the user your parameter names are part of the API they will see them and that makes this more self-documenting and then lastly I have the looping over the interfaces what's wrong with that code the only thing is wrong with it it's it's fragile and we can make it less frigidly there I'm done all right thanks very very much thank you very much Raven clearly there's a lot beyond Pepe and yeah so as a note of logistics on one lane who learned something new okay lunch is downstairs in the expo hall that's room 210 and yeah so go eat in next sessions in an hour
Info
Channel: PyCon 2015
Views: 402,060
Rating: 4.9613309 out of 5
Keywords:
Id: wf-BqAjZb8M
Channel Id: undefined
Length: 52min 5sec (3125 seconds)
Published: Sat Apr 11 2015
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.