5 Good Python Habits

527.49k views3263 WordsCopy TextShare
Indently
Here are 5 good habits you should consider building in Python. ▶ Become job-ready with Python: http...
Video Transcript:
this video was brought to you by IND dentle IO learning python Made Simple how's it going everyone in today's video we're going to be looking at five good habits that you can build in Python for the first one I'm going to be using a module that I created and this module allows us to connect to the internet now suppose I want to test this module out before using it in my script here I'm just going to type in Connect and run this module and in the console I can see that it actually worked quite nicely
great so let's go to the main part of this script and import this function from that module so from module import connect now I'm super happy that I can use it in my script so I'm just going to type in Connect and I'm going to run my main module and voila it's actually connecting but oh no it's connecting twice what did I do wrong well the answer is quite simple every time you import a module it has to load that entire script that means it's reading every line and since at the bottom of our module
we actually ran a function it read that line as well and ran it as a consequence so the first good habit to always have is to always check that name is equal to Main and insert whatever kind of function ality you want to run inside there this will ensure that this code will only be run if I run this module directly and in some code editors it will also give you this nice green arrow which makes it easier to run the correct script so now if I run this inside the module it will run exactly
the same way I was able to test it with no problems and if I were to go back to main.py I can run this script once again and this time it's only going to execute this function once but also if you were quite attentive you would have noticed that I did not run main. Pi I actually reran the module by accident so it doesn't matter what script you're inside using IF name is equal to main can also help ensure that you're running the correct script because thanks to this usually what I do every time I
switch Windows is tap on this Green Arrow when I want to run a script and that will ensure that we are running the current script so this time I'm actually running main.py as you can see in the top right hand corner and finally it also works as a bit of self-documentation because whoever is using your script will know that it was meant to be run if it has if name is equal to main because some modules might just contain information and functions that were only meant to be imported but by providing if name is equal
to main you can easily see that this script was actually meant to be run at a certain point now moving on to the second good habit that I think you should form and this is more of a personal preference and I use this because I see it in a lot of programming languages such as Java please do not leave the video because I mentioned Java but I use this because I see it in a lot of programming languages and in my opinion makes it just a bit more organized so suppose you have some functionality in
your script whatever that is in this script we're just greeting people and saying goodbye one thing I absolutely love to do in all my scripts is Define a main entry point where I can kind of glue all of the functionality I need together so here we have a main function that returns none and then you can test out whatever you want you can greet people you can say goodbye this is where I like to put everything together and then I like to use it in combination with if name is equal to Main and then I
just run main inside there it's just a very clean way to organize your code I mean obviously you can just paste this inside here if that's what you want to do and that works as well but having a main entry point just feels more readable and it also simulates what you would do in other programming languages such as Java and I know this might feel like a lot of boilerplate code but in many code editors you can actually Define live templates or at least in pycharm you can define a live template which can make this
process super smooth for example if I wanted to rewrite all of that all I have to do is type in Main and that would enter both of them then I can enter the functionality that I actually want to run such as greet and buy and for those of you who used to work in Java this is very similar to typing psvm to create that public static void main function that we all used to love moving on to tip number three here I have a function that's called enter club and it takes a name an age
and whether the person has ID or not because we want to check or verify that the person is of the correct age and has valid ID before they enter the club and also since Bob is a troublemaker I decided to add Bob to The Blacklist so if we run into Bob we're going to tell Bob to go away so I've included functionality to prevent Bob from coming inside and also the functionality to make sure that the people have valid ID and that they are 21 years or older then I created a bunch of test cases
to make sure that this actually works so if we were to run this you'll see that some people cannot enter the club such as Bob get out of here but James who's 29 can enter the club and the other two who are underaged and that don't have ID can not enter the club so the function Works quite nicely but I'd have to give it a 1 out of 10 in terms of reusability this only works in a very specific case in case we want to enter the club and this can often be considered a bad
practice because it's handling far too much functionality in a single function so instead of defining all of the functionality inside here we're going to create separate functions for each one of these so for now I'm just going to delete both of these and add an ellipses because I just want to have a placeholder there while I create the other functions and I'm just going to copy and paste in the other functions and explain them quickly so the first one checks that the person is an adult and all I'm doing here is checking that they have
a valid ID and that the age is more than or equal to 21 of course you could take this a step further and create a whole new function for checking how valid an ID is but this will suffice for this example we're just going to consider anyone who has a valid ID and that is more than or equal to 21 to be an adult the second one checks whether the name is equal to Bob and if it's Bob of course we want to remove Bob from the club or prevent Bob from entering so why would
this be considered a better approach to what we did earlier well thanks to this approach we can actually use this functionality anywhere in our script in case we want to use it somewhere else later we don't have to dig around in our huge function to find this functionality we created it in one place and it's Ultra reusable now we can check whether someone is Bob anywhere in our script and while the enter club might not change that much the reusability of our code has increased by a lot so now we can check if is Bob
and handle that accordingly and we can also check if it is an adult and handle that accordingly and if we were to rerun this script it would work exactly the same way so for this good habit all I was trying to say is keep your functions as simple and reusable as possible never convolute your functions with too much code and always try to separate those concerns so that you can make your code AS reusable as possible maybe it's unlikely that you'll check if someone is Bob more than once but you never know and if you
ever want to change this logic you know exactly where to go to do it and the same thing goes for this function over here up next we have a fourth good habit that you should be using in python or actually in modern python because it will save you a lot of trouble in the future and I'm talking about type annotations so here suppose you're creating a number and this is of type integer that's quite straightforward a lot of people think that okay if I just typee in number is equal to 10 that should be quite
obvious that that is an integer with a value of 10 and sure it's quite obvious but whoever is working on your code might for some silly reason insert 10 as a float it's the same value but as you probably know float is not compatible everywhere where an integer is compatible so if we were to type in integer here py charm or our code editor will give us some syntax highlighting telling us that hey don't do that because you might break the program and in some extreme cases your developers or your colleagues might even enter 10
as a string providing this type annotation warns us far ahead of time that we're doing something completely ridiculous and maybe for the basic types it might be quite obvious in most cases but what happens when you start getting more complex types then it just gets easier and easier to insert the wrong type and of course if you insert the wrong type your program's not going to function as expected but let's look at a different example and in this example we're going to have a function that uppercases every element and this function does not have any
type annotations and again this is quite a simple function but there's a lot wrong with it such as we know that we can insert elements but what kind of elements can we insert well if we were to insert integers for example this function will raise an exception because you cannot up per integers that's not an operation that makes sense but we're not going to get any warnings either from the code editor so we're just going to have to run it and get that exception before changing it to something that actually makes sense we have no
documentation here and of course for those of you who really like to waste time on writing obvious documentation you can add a dock string that explains exactly what the user should do or you can be explicit from the beginning and you can say elements of type list of type string and that this returns a list of type string thanks to these type annotations we are self-documenting this function we're telling the developer or the user exactly what they have to enter and what they're going to get out they're not going to have to experiment with numbers
they're not going to have to read documentation they just have to take a quick glance at the function signature to understand what it does I'm not saying that documentation is a bad thing I'm just saying that redundant documentation is a bad thing and also and and added benefits of using type annotations is that we get more context so thanks to adding list of typ string here pycharm was able to infer that this was an element of type string meaning it will give us the context actions for Strings if we did not have this type annotation
pycharm would have no idea what that is I mean of course that can be an integer it can be a float it can be a Boolean pycharm has no information regarding what elements are so that's just a simple bonus to using type annotations is that we get better context actions or more appropriate context actions and once again if we ever try to pass in the wrong data types pycharm is going to complain here I have two variables that do the exact same thing but with one of them I decided to annotate it as list of
type integer but here we explicitly told pycharm that we're returning a list of type string without this type annotation we would get no warnings and then we would run that script before realizing that we're not getting this list of integer back and the silly part is that we can also add 1 2 3 and we will still get no warnings and a lot of silly people will say well it's quite obvious you can't upper an integer well in programming obvious is never obvious enough there's always going to be someone who misinterprets something in the past
four years of teaching I've seen the most ridiculous code in the universe never underestimate what people think never think that your code is ever going to be too obvious because people are always going to misinterpret what they read whether it's because of a language barrier whether it's because they're tired whether it's because you wrote your documentation very poorly it's never going to be as obvious as you see it so the best thing we can do as developers is to be extra obvious with everything we write although sometimes the code editors are not going to catch
everything for example we might have this sample list of typ integer and obviously this does not only contain integers it also contains strings but why don't we get any warnings and that actually really depends on the capabilities of your code editor personally I have no idea why py Cham cannot recognize that we have a wrong data type inside this list so if you really want to take type annotations seriously you're going to have to install a static type Checker such as mypie so pip install mypie but once I've installed mypie the mypie extension in py
Chom is going to take effect so it's going to highlight what I did wrong for example A and B should not be part of this list of integer my Pi can recognize this but py charm cannot but in other cases you might even just want to run my Pi directly so my pi main.py and this will scan our script and check for any error is and usually it's quite detailed so it will say list item zero has incompatible type of string but we expected an integer and the same thing for list item number two so
type annotations are completely optional and your code will run the same with them or without them even if you insert the wrong type annotation your code will still run but because of type annotations my code rarely fails because I know exactly what I'm doing I know exactly what type I'm inserting and if I do something silly I'm going to get a warning that allows me to fix it before I even run the script so in other words I don't really make these silly accidents thanks to type annotations and the final good habit I want to
share with you guys today is list comprehensions I absolutely recommend you start using list comprehensions if you aren't already because not only are they faster but they can also be easier to read in certain scenarios anyway to demonstrate it I'm going to create a list of people which just contains a few names such as James Charlotte Stephanie Mario and Sandra and what I want to do here is get back all of the names or all of the people that have names longer than seven characters and to do that I need to create a new list
and then I need to check for each person in these people if the length of that person is more than seven then we can append that person to the new list and obviously if I want to see the result of this operation I'm going to have to print it to the console so now if we were to run this we should get Charlotte and Stephanie back because those were the only two names that were longer than seven characters but let's perform this same operation using a list comprehension so here I'm going to type in Long
names and that's going to Shadow the name above but who cares for now and actually apparently my pie cares a lot so I'm just going to comment this part out anyway we have this variable here and we're going to create the same list using a list comprehension so here I'm going to type in p for p and that's just going to stand for person in people if the length is more than seven and it actually has to be the length of p and that took no time to create and also saved us three lines of
code which is epic and if we were to run it we would get the exact same output and while I wouldn't recommend this because it starts to look very cluttered you can even enter it directly into your print statement and it would work exactly the same way although at the moment there is a trade-off and that is that this can be considered less readable because right now we have P for p and people if the length of p is more than seven it would take any developer a moment to understand what that actually means but
thankfully we also have a very descriptive variable name that should give them an idea that the length of each person should be longer than seven to be considered a long name so in this scenario I would absolutely opt in for this version of of the list creation and if you want to be even more specific you can change this variable name to names then you can just type in for name name name and this might even be considered more readable than what I had earlier because now we know exactly that these are names and that
the length of the name has to be more than seven it kind of provides some better documentation for this list comprehension but anyway that's actually all I wanted to cover in today's video do let me know whether you have any good habits of your your own but otherwise as always thanks for watching and I'll see you in the next video
Copyright © 2024. Made with ♥ in London by YTScribe.com