Write Python Code Properly!
Summary
TLDRThis video tutorial focuses on the essential aspects of Python coding according to PEP 8, the Python style guide. It covers key conventions such as line length, indentation, naming conventions for variables, constants, modules, functions, classes, and exceptions. The presenter also discusses auto-formatting tools like Black, spacing rules, quotation mark usage, parameter naming, import statements, string operations, and best practices for comments and exception handling. The aim is to improve code readability and consistency, even though adherence to PEP 8 is not mandatory for code correctness.
Takeaways
- 📘 The video discusses the importance of adhering to PEP 8, the Python style guide, for writing consistent and readable Python code.
- 🛠 It's not incorrect to deviate from PEP 8, but doing so can lead to inconsistency, especially in large organizations.
- 🔗 A link to PEP 8 is provided in the video description, and it's authored by Guido van Rossum, Python's creator.
- ⚙️ The video recommends using an auto-formatter like 'black' to automatically adhere to PEP 8 guidelines, saving time and effort.
- 📝 PEP 8 suggests a maximum line length of 79 characters, with the 80th character being where the line should wrap.
- 🔑 For indentation, PEP 8 recommends using four spaces, avoiding tabs, to prevent potential errors and maintain consistency.
- 🔡 When naming variables, functions, and methods, snake_case should be used, while classes and exceptions should follow PascalCase.
- 🔠 Constants should be in all capitals with underscores separating words, and are typically placed at the top of a Python file.
- 📑 The video emphasizes the importance of consistent styling, such as the use of quotation marks, over strict adherence to every rule.
- 🚫 It advises against using wildcard imports (e.g., 'from module import *') as it does not clearly define what is being used from the module.
- ➡️ For string operations, using methods like `startswith` or `endswith` is preferred over slicing for checking prefixes or suffixes.
Q & A
What is the main focus of the YouTube video?
-The main focus of the YouTube video is to show the proper way to write Python code by following the Python conventions and the most important parts of the PEP 8 style guide.
Who wrote the PEP 8 style guide?
-PEP 8 was written by Guido van Rossum, the inventor and creator of Python.
Why is it important to follow PEP 8 guidelines in a large organization?
-Following PEP 8 guidelines in a large organization ensures code consistency, which can prevent some people from being upset about inconsistencies in how Python code is written.
What is one of the main rules in PEP 8 regarding line length?
-One of the main rules in PEP 8 is that any line in Python code cannot exceed 80 characters.
What tool does the video recommend for auto-formatting Python code in VS Code?
-The video recommends using 'black', a popular formatter for Python, for auto-formatting code in VS Code.
How should variables be named according to PEP 8?
-Variables should be named using snake_case, which means separating words with underscores and using all lowercase letters.
What is the naming convention for constants in Python?
-Constants should be named using all uppercase letters and snake_case.
How should functions be named according to PEP 8?
-Functions should be named using snake_case, similar to variables.
What is the correct way to name classes in Python?
-Classes should be named using PascalCase, which means capitalizing the first letter of each word without underscores.
What should be the first parameter name in instance methods and class methods?
-The first parameter in instance methods should be named 'self', and in class methods, it should be named 'cls'.
How should top-level functions and classes be spaced in a Python file?
-Top-level functions and classes should be separated by two blank lines.
What is the PEP 8 guideline for spacing around operators?
-PEP 8 recommends having spaces around operators, with the same number of spaces on each side of the operator.
How should default values for parameters in functions be formatted?
-Default values for parameters should have no spaces around the equal sign.
What is the recommended way to import modules in Python?
-Modules should be imported at the top of the file, each on a separate line, and using 'import *' is discouraged.
How should strings be enclosed in Python, according to PEP 8?
-Strings can be enclosed in single or double quotation marks, but consistency should be maintained throughout the code.
What is the preferred method for checking if a variable is 'None'?
-The preferred method is using 'is None' rather than '== None'.
What is the correct way to check if a string starts or ends with a specific substring?
-The correct way is to use the '.startswith()' and '.endswith()' methods instead of string slicing.
Outlines
📝 Introduction to Python's PEP 8 Style Guide
The script begins with an introduction to a Python coding tutorial, focusing on adhering to the PEP 8 style guide, authored by Python's creator, Guido van Rossum. The guide, while extensive and covering many aspects of Python coding conventions, will only be partially covered in the video. The presenter emphasizes that while adherence to PEP 8 is not mandatory for correct Python code, it is important for consistency, especially in large organizations. The video is sponsored by Harbor DB, a hybrid SQL/noSQL database, which is introduced before the main content begins.
🔧 Setting Up Auto Formatting with Black in VS Code
The presenter demonstrates how to use an auto-formatter in Visual Studio Code (VS Code) to adhere to PEP 8 guidelines, specifically the rule that no line should exceed 80 characters. The auto-formatter 'black' is recommended and installed via pip. The tutorial includes instructions on how to set up 'black' as the default formatter in VS Code and how to enable auto-formatting upon saving a file, which simplifies the coding process by automatically handling line lengths and other formatting issues.
📐 PEP 8 Guidelines: Line Length, Indentation, and Consistency
This section delves deeper into PEP 8, discussing the importance of line length not exceeding 80 characters and the use of four spaces for indentation. The presenter advises against using tabs for indentation to avoid potential errors. The emphasis is on consistency in coding style, whether it involves quotation marks, spaces around operators, or other stylistic choices. The section also introduces the concept of snake case for variable names and all-uppercase naming for constants, with examples provided for clarity.
📚 Naming Conventions for Variables, Constants, Modules, Functions, Classes, and Exceptions
The script continues with an explanation of Python's naming conventions. Variables should use snake case, while constants are in all-uppercase with underscores separating words. Modules should be named in lowercase, with words separated by underscores if necessary. Functions follow the same naming as variables, while classes and exceptions should be named using Pascal case, with the first letter of each word capitalized. The presenter also discusses parameter naming conventions for methods in classes, emphasizing that the first parameter for an instance method should be 'self', and for a class method, it should be 'cls'.
🛑 Spacing Rules and Import Statement Conventions
The paragraph discusses spacing conventions in Python coding, including spacing around classes, methods, and functions, as well as the proper placement of import statements. It is recommended to have two blank lines between top-level classes and functions and one blank line between methods within a class. Import statements should be at the top of the file, with each import on a separate line, except when importing multiple items from the same module. The use of wildcard imports is discouraged, and a special note is made about placing imports after a module docstring if one is present.
🚫 Common Mistakes with Whitespaces and Quotation Marks
This section highlights common mistakes made with whitespaces in Python coding, such as improper spacing around brackets, commas, and function calls. It stresses the importance of consistency in spacing around operators and equal signs. The presenter also covers the correct use of single and double quotation marks, emphasizing that while both are allowed, one must be used consistently. An exception is made for triple-quoted strings, which should always use double quotation marks. The paragraph concludes with examples of incorrect whitespace usage and the correct practices.
👀 Correct Usage of Operators and Inline Comments
The script addresses the proper use of operators, including showing the correct precedence and spacing around them. It points out common errors and provides examples of the correct usage, such as having spaces around assignment operators and avoiding uneven spacing around binary operators. Inline comments are also discussed, with the presenter explaining the correct placement and formatting, including at least two spaces from the code and one space after the hash sign, starting with a capital letter unless it doesn't make sense semantically.
🔄 Checking Values and Using String Methods
The final paragraph covers various coding conventions related to checking values and using string methods in Python. It advises using 'is None' for explicit checks against None and 'is not' for negation checks, instead of '==' or '!='. The paragraph also discourages the use of empty except blocks and recommends catching specific exceptions. Additionally, it suggests using string methods 'startswith' and 'endswith' over string slicing for checking prefixes and suffixes, as they are considered more accurate and performant. The video concludes with a reminder that only a subset of PEP 8 has been covered and encourages viewers to like and subscribe for more content.
Mindmap
Keywords
💡PEP 8
💡Guido van Rossum
💡Consistency
💡Auto-formatter
💡Indentation
💡Naming Conventions
💡String Quotes
💡Docstrings
💡Imports
💡Whitespace
💡Comments
💡None Check
💡Exception Handling
💡String Methods
Highlights
Introduction to the importance of adhering to Python's PEP 8 style guide for writing clean and consistent code.
PEP 8 is a comprehensive style guide authored by Python's creator, Guido van Rossum, with conventions and best practices.
Highlighting the common mistakes made by developers when not following PEP 8, affecting code consistency and readability.
The significance of line length not exceeding 80 characters in Python code for better readability and maintenance.
Demonstration of using auto-formatting tools like 'black' to automatically adhere to PEP 8 guidelines, saving time and effort.
Explanation of how to set up auto-formatting in Visual Studio Code for Python development.
The rule of using spaces for indentation in Python, with a standard of four spaces per indentation level.
Consistency in code styling is emphasized as more important than strict adherence to PEP 8 where readability is concerned.
Variable naming conventions in Python, advocating for snake_case to avoid common errors like camelCase or PascalCase.
Constants in Python should be named in all upper case with underscores separating words, signifying their unchanging nature.
Module naming conventions suggest lowercase with underscores for separation, aligning with variable naming but preferring single words.
Function naming follows the same snake_case convention as variables, contrasting with class naming which uses PascalCase.
Parameter naming conventions for methods in classes, emphasizing 'self' for instance methods and 'cls' for class methods.
Spacing conventions for classes, methods, and functions, advocating for two blank lines between top-level definitions and one line for methods within classes.
Import statements should be placed at the top of Python files, with exceptions only for module docstrings, and should not mix distinct imports on the same line.
Avoiding wildcard imports and the use of specific imports from modules for clarity and better code maintenance.
Quotation mark usage in Python, with no preference between single and double but a requirement for consistency within a codebase.
Triple quoted strings for docstrings should always use double quotation marks, according to PEP 8.
Common whitespace mistakes in Python coding, such as incorrect spacing around brackets, commas, and operators.
Proper usage of spaces around assignment operators and equality checks, emphasizing consistency and correct operator precedence.
The correct way to check if a variable is equivalent to 'None' using 'is None' instead of '==' to avoid false positives with other falsy values.
Using 'is not' instead of 'not is' for checking inequality, although both are functionally equivalent, 'is not' is the conventional choice.
The importance of catching specific exceptions in try-except blocks rather than using a general except block to improve error handling.
Using string methods 'startswith' and 'endswith' over slicing for checking string prefixes and suffixes for better performance and clarity.
Conclusion summarizing the key points covered in the video, highlighting the most important and commonly mistaken aspects of PEP 8.
Transcripts
Hello everybody and
welcome to another
YouTube video. So in
today's video, I am
going to show you the
proper way to write
Python code. And when I
say that, what I mean is
I'm going to show you
the proper Python
conventions and go
through the most
important parts of the
Python style guide,
which is known as pep
eight. Now pep eight is
a very large Python
style guide. I'll leave
a link in the
description to it. It's
written by Guido, who is
the inventor and creator
of Python. And while
there's just a ton of
things in there,
obviously I can't cover
everything, but I'll
show you kind of the
things that I see people
making the mistake on
most commonly and what I
consider to be the most
important things that
you kind of need to know
from that guideline.
With that said, if you
don't follow that
guideline, it's not
necessarily incorrect.
Your code is not wrong.
It just does not adhere
to it, and some people,
If you're working in
maybe a large
organization, for
example, may be a little
bit upset that you're
not being consistent
with how Python code
should be written. So
with that said, let's go
ahead and get into the
video after a quick word
from our sponsor, before
we get started, I need
to thank Harbor DB for
sponsoring this video.
Harper DB is a hybrid
SQL slash no SQL
database that is
accessed to be a single
rest API endpoint.
Harper DB provides a
scalable and flexible
database that improves
your app's performance.
With the ability to run
sequel on Jace on data,
you no longer have to
pick a database based on
the structure of your
data. Harper DB will run
anywhere and ingest any
type of data. At scale,
with Harper DB, you can
perform all crud
database operations
using only one single
endpoint. You can
execute sequel on Jason
data and insert data via
Jaison CSV or sequel
queries. Harper DB, Elsa
removes the headache of
database connectivity
and set up by providing
a geo distributed
database that improves
speed performance and
latency. Harper DB is
incredibly fast allowing
one single node to
handle up to a hundred
thousand requests per
second. It can also
globally replicate data
at the speed of the
internet to put this
into perspective, Harper
DB benchmarks at speeds,
37 times faster than
Mongo DB. If you need
any help along the way,
Harbor DB has detailed
documentation and tons
of customizability for
more advanced
developers. Thanks again
to Harper DV for
sponsoring this video,
spin up a free forever
instance today, like
clicking the link in the
description. All right,
so let's go ahead and
get started in front of
me here. You can see, I
have pep eight, the
style guide for Python
code. This is available
on the Python website.
It's written by Guido
and I just quickly
wanted to show you what
the table of contents
looked like. So you can
see how much stuff is
actually in here. So
obviously I won't go
through all of this. As
I mentioned, I'm
probably covering, you
know, 10% of what's
actually in this
document, but a lot of
the stuff in here is
just really nitpicky and
something that you
probably don't really
need to know. Anyways,
there you go. That is
the guide. So what I'm
going to do now is go to
vs code, which is the
IDE I'm going to use for
this video. And the
first thing I want to
show you is just how to
make your life a little
bit easier if you're
trying to write code
according to the pep
eight style guideline.
So one of the main
things in the pep eight
style guideline is any
line cannot exceed 80
characters in Python. So
to give you an example,
take a look at this. I
have this long function
name with long
arguments. Obviously
this is just an example.
And if we go here and
look at the bottom, we
can see this as 116
characters. So really
what the pep a guideline
wants us to do is split
this line up, such that
it only has max 80
characters on the first
line. So we could do
something simple like
this, right? And then
kind of get the
indentation correct
here.
And then that would be
fun. However, if we
don't want to have to do
this ourself, what we
can do is actually use a
format or an auto
format, or where, when
we save our file, it
will automatically fix a
ton of formatting issues
for us. So I'm just
going to show you how to
set that up quickly,
such that you don't have
to automatically format
and change the line
length and do all that
kind of stuff. So if
you're working in vs
code, then what you can
do is start by
installing an auto
format or using PIP,
which is called black.
Now black is probably
the most popular format
or for Python, but the
way you do this is PIP
install and then black.
Now I'm not going to
exactly go through what
PIP is. If you're not
familiar with that, but
try this command. If it
doesn't work, you can
try PIP three PIP, three
should work. If you're
on Mac or Linux. And
then if that doesn't
work, you can do Python,
hyphen M PIP install.
And if that doesn't work
Python three hyphen M
PIP install black, all
right. So once you've
installed the auto
format or with PIP, then
if you're working in vs
code, what you're going
to need to do is go to
settings.
So I'm going to go to
settings settings, and
then you're going to go
for the Python and this
should be the format
provider like that. So
if you look up Python
format provider, then
what you're going to do
is select black here. By
default, you have auto
pep, eight doesn't work
as well as black. So I'm
going to select black.
And now if you go to
format here and you
check the format on
save, so format of file
and save so
automatically format it
whenever you save the
file, what's going to
happen. When I save this
file is going to auto
format this line for me.
So you can see it's made
it such that this line
here is exactly 80
characters long. Just
want to show that to you
because that saves you a
lot of time when you're
actually trying to write
code, according to the
pep eight style
guidelines, and it will
fix other things for you
as well, not just line
length. All right. So
now that I've covered
the auto format or we'll
start getting into the
pep eight guideline more
specifically. So the
first thing you saw is
that the maximum line
length is 80 characters.
So as soon as you get to
80 characters, you
should go down to the
next line.
Technically the maximum
line length is 79
characters, but the last
character on the line
where you go down to the
next one is the 80th
character, right? And
then the next important
rule in the pep eight
style guideline is the
indentation should be
using spaces and you
should be using four
spaces for all of your
indentations. So you can
see down here, I have
spaces and I have four
and I'm using spaces. So
just make sure you
indent using spaces and
four spaces, a lot of
editors actually indent
using Tam. It's fine if
you indent using tab,
but it can cause some
issues and you can get
some weird errors. So
it's always preferable
to use spaces and four
spaces. All right, now,
moving forward, the rest
of the rules that I'm
going to show you here
are typically considered
the best practice and
what you should use.
However, there's always
exceptions to these
rules and if they make
your code less readable
or they don't make sense
to implement, then it's
always fine to kind of
ignore them and go with
whatever style that
you're using. Really the
most important thing
when you're writing any
code, not even just
Python code is whatever
style you go with. It's
consistent. So if you
use single quotation
marks for strings,
always use single
quotation marks for
strings.
If you're doing a space
around your operators,
always use a space
around your operators,
just make sure that
whatever you're doing is
consistent. That's way
more important than
following the strict
rules that I'm going to
show you here. All
right. So now what I
want to do is get into
Nate. All right. So
let's start with the
naming convention for
variables. So the naming
convention for your just
typical variables in
Python is you snake case
or word underscore word,
convention, case,
whatever you want to
call it. So what I mean
by that is if you have a
variable, that is two
words, sorry, this
should be lowercase.
Then what you want is
something like this
hello world, as opposed
to something like this,
this would be the
incorrect case. This is
camel case. Instead you
want to use snake case.
This is probably the
most common error I see
in Python. Uh, people
use camel case when they
should really be using
snake case for their
variables. Now, some
people will also do
something like this.
This is known as Pascal
case. This is also
incorrect. You don't
want to do that for
variables. Now, if you
add a third word here,
same thing, you would
just separate again with
another underscore.
There you go. Simple.
That's all you need to
know for the naming
convention for
variables. Now, the
naming convention for
Constance is to do all
upper cases and then
snake case.
There's probably a name
for this, but it looks
something like this. So
let's say you had a
constant variable. You
would name it like this.
Notice it's highlighting
in a different Cub. Now
he constant variable is
a variable that stores a
value that you do not
expect to change in the
program. And that relate
should not change in the
program at all. So an
example of a constant
might be something like
a color that you're
going to use to for
styling your website or
styling a game or
something that's never
going to change. In this
case. Again, you do an
all capitals and then
you would, you know, put
whatever the value of
the constant is. And
then this variable
should never have its
value changed. It's
should only ever just be
used in the program as a
constant. Now there's
not really a way to
enforce that this is not
going to be changed in
other programming
languages. There is, but
regardless, when you
have a constant, you
normally want you to put
this at the very top of
the program below any
import statements and
then have it in all
capitals. Now, if you
had two words, you could
do something like this
BG underscore color.
This would be correct
standing for a
background color. You do
it with an underscore in
all capitals. And again,
this goes at the top of
your program below any
imports statements.
Okay?
So that is the naming
convention for
constants. Now the
naming convention for
modules, that would be
the actual Python file
itself is to have it all
in lowercase. So usually
want one word, all
lowercase. But if you do
need to have multiple
words, then you want to
separate that with
underscores. So just
like you would name a
variable, that's how you
name your modules,
except it's preferred
that you just have one
word and you don't have
multiple words. If you
do have multiple words,
separate them with
underscores. Now the
naming convention for
functions is the same as
four variables. So if I
have my hello, oops,
underscore world
function, this is
correct. You do not want
to name a function low
world like that. Again,
this isn't really
incorrect. You can do
it. There's nothing
wrong with doing that.
It just doesn't follow
the Python convention.
Okay. So that is
functions. Now, lastly,
we need to go over
classes and exceptions.
So when you name a
class, you want this to
be in Pascal case. That
means an uppercase on
the first word,
uppercase on the second
word. And you're having
them kind of in camel
case notation. So let me
just type it out and
you'll see what I mean.
Let's name this base
class or something. This
is what you want. So you
want a capital on the
first word? No, no
underscore and a capital
on the second word.
And that's how you name
a class. Okay. Pretty
straightforward. And
then if you just had one
word, you would just do
it like that. Now,
whenever you name an
exception, same thing
you want it to be in
Pascal case. Now, the
reason for that is an
exception is a class in
Python. And so it should
have the same naming
convention. So if you
were to create an
exception, let's just
say, you know, this is
called face exception or
something. I think that
that's actually a
built-in class in
Python. Let's just call
this X exception. Then
you would name it like
this. Hopefully that
makes sense. But that's
really all of the
important naming
conventions in Python
that you need to know.
All right. The next
thing that I want to
cover here is just some
parameter naming
conventions related to
methods in classes. So
let's say we have a
class. We can call this
class test and let's say
we have a test method.
And this method is an
instance method. Then
the first parameter for
this method should be
named self. So a lot of
people know this and
they probably actually
think you have to name
this self, but
technically I could name
this S I can name this
inst or something,
whatever you name that,
whatever I want, it will
still work. It will
still hold the instance,
the method was called
on, but by convention it
should always be named
self.
So again, the first
parameter in an instance
method should always be
named self. Now in the
same way, if you have a
class methods, so let's
go at class method like
that. And then we
define, I don't know,
let's go CLS underscore
method B first parameter
here. It should be named
CLS. So again, a
convention first prouder
of any class method
should be named CLS
standing for class.
There you go. Simple
enough. Okay. So that
was all I needed to
cover for this. Just
make sure you self NCLs
as you are for first
parameter values for
class and for instance
methods. All right. So
the next convention I
have, you has to do with
spacing out classes,
methods, and functions.
Again, people mess this
up all of the time, even
if you decide not to
follow these rules, just
make sure you stay
consistent with how you
decide to space these
out. So let's define a
few classes here and
functions and methods.
So I'm going to show you
what I mean. So let's
have a, our class Fu and
let's define in a knit.
Okay. And we can just do
a pass in here. Let's
define a Fu method and
let's do a pass inside
of here. Okay. Let's
define a function. We'll
call this bar and let's
do a pass. All right. So
this is what I have
right here.
Now, any top level
functions or classes
should be separated by
two white spaces or
sorry, two blank lines.
So what I mean by that
is that this is correct.
You want to separate
your classes with two
spaces. Here are two
blank lines and then
same thing here with the
function. Now, the
reason for this is these
are in the top level,
top level, meaning kind
of furthest left
indentation level. These
are all global to this
file. And so that means
you space them out with
two blank lines. However
methods inside of the
classes are spaced out
with one blank line. So
that's really all you
need to know here. Just
make sure all of your
functions and all of
your classes. Let's just
do another one. Here,
have two lines in
between them. If they're
in the top level, if
they're nested inside of
something, then that
might change. And if you
have methods here inside
of a class, you separate
them with one line. All
right. So next I'm going
to talk about imports.
Now, import should
always go at the very
top of your file, unless
there's some specific
exception, in some
reason why you can't
import something at the
very top of your file,
but you always want all
of your imports at the
top of the file. And
they're just on the next
line from each other.
So let me show you what,
I mean, you have
something like import S
import sys, this is
correct. You've imported
things properly. Now you
can actually import
things on the same line.
So import OSTP and
import sys, but this is
not the Python
convention. And pep
eight says you should
not do this. So I should
not import two distinct
modules on the same
line. I should split
them into two lines like
this. And again, top of
your program, now the
exception is that if
you're going to be
importing things from a
module, you can import
multiple of them on the
same line. So maybe I
say from OSTP import
path and import, I don't
know, stat or something.
I dunno what other thing
I would import for the
less, but you get the
idea. This is fine
because I'm importing
two things from one
individual module. And
so I can import them on
one line. That is okay.
You don't need to do
something like from S
import if I can type
this stat like that.
Okay. So that is kind of
the basic rules with
import. Now, one more
important thing is you
should not use the wild
card import. What I mean
by that is you shouldn't
do something like from,
uh, oh, S import asterix
that is incorrect. You
shouldn't do that. This
is just not good to use
because this will import
everything.
And it doesn't clearly
define what parts of
OSTP you're actually
going to be using in
your program. So just
avoid this, if you can.
All right. So one more
important note here, the
only time when you're
not going to have your
import statements and
let me change this to a
proper import statement
at the top of your
program is if you have a
module doc string. So if
you have a module doc
string, this is a string
that describes what's in
this pipe on module.
Then your imports can go
after that. Otherwise
I'm going to go at the
very top of the program.
And then after your
imports, you're usually
going to have any of
your globally defined
variables and constants,
and then any of your top
level functions and
classes. All right, so
now I'm going to cover
strings and specifically
what type of quotation
marks you can use. So
this is a big issue in
Python as well. And I'm
very guilty of doing
this, but in Python, the
single and double
quotation marks are
completely equivalent.
And there actually is no
preference on whether
you use the single or
the double quotation
marks. The only rule is
if you've use double
quotation marks, you
should always use double
quotation marks. And if
you single quotation
marks, you should always
use single quotation
marks.
The only exception to
that would be if you
need to actually embed a
single or double
quotation mark inside of
a string. So it's
preferential. If you
want to put a double
quotation mark inside of
a string that you wrap
the string in single
quotation marks. So if I
actually wanted to say
something like, hello,
double quotation mark,
for some reason that I
would put that inside of
single quotation marks
and in the other way
round, if I wanted to
use a single quotation
mark, then I would wrap
that inside of double
quotation marks. Now
that is opposed to doing
this. So you can
actually use an escape
character in Python to
escape this quote, such
that this string is
maintained, but it's
preferred to just wrap
with the opposite
quotation marks rather
than using an escape
character. Although
sometimes you do need to
use the escape
character. So that's
kind of the role with
quotation marks, just be
consistent on whatever
set you decide to use.
Doesn't matter if you
single or double, there
is no preference in, at
the style guidelines.
However, when you are
writing a doc string or
a triple quoted string
like this, you should
always use a double
quotation marks. Don't
know why that's a thing
I would have imagined
you could use single or
double as long as you're
consistent, but it says
you should always use
double quotation marks
whenever you're writing
a triple quoted string.
All right, so next, I'm
going to talk about
incorrect usage of white
spaces. So I'm just
going to paste a bunch
of examples here and
then show you what I
mean on the incorrect
usage of white spaces.
So let's look at this
one. For example, we
have some functions,
spam ham indexing one,
and then we're creating
some dictionary here.
This is correct. You do
not want to have white
spaces between a, a
bracket, race,
parentheses, whatever it
may be, and whatever
comes after that. So
looking at this, this
would be incorrect. You
do not want to have
spaces like this. You
can see all of the white
spaces showing up, just
don't do that, make
everything look like
this. All right. The
next example is this.
You do not want to have
white between a trailing
comma and a closing
parentheses. So if you
have something like
this, you want to leave
it like this, right? You
don't want to have a
space between the
trailing comma and the
closing parentheses, the
next situation in which
you do not. I want to
have a white space is
right here. So you do
not want to, I have a
white space in between a
function call or in
between something and an
opening prophecy
followed by arguments to
some call. So whether
this is a function,
whether this is a class,
doesn't matter, you
don't want to have this.
So don't separate your
arguments from the
actual call that you're
making. This is the
correct way that you
should call a function,
initialize a class,
whatever it may be. All
right? So this is the
next example of a white
space usage that you
want to know. The first
thing to note here is
when you're declaring a
variable, you always
want to have at least
one space on each side
of the equal sign. So
this is correct. Notice
this is incorrect,
right? Because we don't
have any spaces on each
side of the equal sign
like that. Now, another
thing is when you're
using a operator like
the plus sign or the
minus sign, typically
you are going to want to
have spaces on either
side of this operate.
The only time in which
you shouldn't have, that
is when you're trying to
show the precedents of
operators, then you can
actually kind of jam the
operands together with
the operator. Seems a
little bit weird, but
have a look at this
example right here. So
in this situation, it's
fine to have a plus B
and a minus B user
trying to show these
happen before the
multiplication. So
that's the only time
when it's okay to kind
of mess with the spacing
here, uh, is when you're
going to try to show the
precedent of operators.
Now, when you're using
the multiplication sign,
same thing, it's fine to
have two things squished
together here, because
we're trying to show
that these are going to
happen before the
addition operation.
Okay? When you're using
something like plus
equals or minus equals,
you want one space on
each side of this
operator. And when you
are using any operation,
you want the same amount
of space on each side of
the operator. So
something like this is
no good because I have
no space here and one
space here. So whatever
you do, just make sure
it's consistent. You
should always have the
same number of spaces on
the left and right-hand
side of any operative.
Now, if you're looking
at this, this is
considered incorrect.
First of all, because
you don't have the same
number of spaces and you
should always have one
space here. This one is
considered incorrect
because you're not
properly showing the
precedence of operators.
I make this mistake all
the time, but you should
do X times two minus
one, same thing here.
You're not correctly
showing the precedence
of operators. So you
should do that. And
that, and then this one
you could argue whether
it's incorrect or not,
but again, it wants you
to do this, to show the
precedents of the
operators. All right?
So the next example here
kind of contradicts what
I just showed you, but
this is specific to
white spaces in the
default value for
parameters in a function
or for arguments. So
this is correct. The
reason this is correct
is because you do not
want any white spaces on
the left or right hand
side of the equal sign.
When you're defining the
default value of a
parameter, same thing.
When you are calling a
function with default
values or sorry, you're
assigning a arguments.
That's what I meant to
say. You want to make
sure you don't have any
space so you can see why
this is incorrect here.
We would need to remove
the spaces in all of
these, for this to now
follow the pep eight
style guide. All right.
So now I'm going to talk
to you about inline
comments. This is super
simple, but these are
things again that people
mess up a lot. And it's
going to paste in an
example here. So you can
see this is correct, and
this is incorrect. So an
in-line comment is a
comment that goes on the
same line as some
expression, variable,
whatever. In this case,
this is correct because
we have at least two
spaces between the line
and the comment. The
comment has at least one
space between the pound
sign and what the actual
content of the comment
is. And the comments
starts with an opera
case.
So that is kind of the
rules for an in-line
comment, at least two
spaces between it and
whatever the expression
is on that line. One
space after the pound
sign, and then you want
it to start with a
capital, unless it
doesn't make sense. I
would start with a
company. Now this is
wrong because we only
have one space here. We
don't have a space
between the pound sign
and then full on to be
even more wrong. We
could do this. This
would need to be a
capital to make this
correct. We would need
it to look like this. So
again, these rules
aren't super, super
strict, but just make
sure you're consistent
with however you're
doing your inline
comments. If you only do
one white space, that's
fine, but just make sure
you always only do one
white space. All right.
So the next convention I
have for you is a quick
one, but this has to do
with checking. If a
value is not. So a lot
of times what people
will do to check if some
variable is none is
they'll do the
following. If X like
that, now this is fine.
This will actually tell
you if X is equal to
none, but it will also
tell you if X is false.
So this is why you want
to be explicit.
If you're checking, if a
variable is equal to
none, because if I do
something like X equals
false, this, if
statement will still
trigger. If I do
something like X equals
zero, it will still
trigger by do something
like X is equal to an
empty string. This will
still trigger. And so if
you only want to check,
if the value of X is
equal to none, then you
should say, if X is none
like that, now it's
important that you do is
none and not double
equals none. This is
just another rule you
want to make sure you're
never checking. If
something is equal to
none using double equal
signs, you want to use
it. So that's kind of
the only real here when
you're checking
equivalents with none,
be explicit and use is
none as opposed to
double equals none. All
right. So the next
convention here is
pretty simple, but if
you were trying to
check, if the value of
something is not
something then you want
to use is not, not, not
is now. This is not
specific to checking the
value. None you could
check, you know, let's
just say like X, uh,
this would be the exact
same thing. And let me
just make sure I use the
same quotation marks
here. You want to make
sure you're using is
not, not, not is now.
These will actually give
you the exact same
result.
It just, the convention
to use is not. Now the
reason I'm saying
that'll give you the
same result, even though
it looks like it won't
is because the knot is
going to be applied to
Fu is X not to food. So
it's not going to negate
Fu and then check not Fu
is X. So it won't do
this. What it will
actually do is this
okay? So it is the same
result, but you just
want to make sure you're
using is not alright. So
the next convention here
is really simple, has to
do with a try and accept
block. And really the
only thing you need to
know here is you should
always accept a specific
exception. A lot of
people don't do this. I
don't do this all the
time. In fact, all of
the rules I've stayed
here. I've broken at
some point in time, but
you always want to make
sure you're accepting a
specific exception, not
doing an empty except
block like this. There
was a bunch of different
reasons why that's the
case. I won't really get
into them, but just make
sure you're almost
always accepting a
specific exception. And
if you need to accept
multiple specific
exceptions, then do
another, except like
this, don't just do an
empty except block like
that. All right. So this
is actually our last
convention or rule right
here.
And this is, if you were
trying to check if a
string starts with or
ends with something you
should use the dot
starts with or dot ends
with as opposed to using
a string slice. So these
are just better. These
are apparently supposed
to be more accurate and
more performance than
using a slice. And so
that's the reason why
you're supposed to use
them. This is weird. I
didn't know about this
at all. This is one of
the main things that I
was like, whoa. Okay.
That's interesting. I
hadn't heard that
before. So just check or
not check use starts
with or ends with, as
opposed to using a
string slice when you
want to check the prefix
or suffix of a string.
So with that said,
that's pretty much going
to wrap up this video.
Again, I only covered a
small subset of the pep
eight guideline. Just
wanted to go through
what I thought was kind
of the most interesting,
most important and
commonly mistaken stuff
in Python. Hopefully you
guys found some value
from this video, if you
did make sure they like
subscribe to the channel
and I will see you in
another one..
Ver Más Videos Relacionados
Python Syntax - Everything you need to know!
02 - Expressions A - Python for Everybody Course
How To Create Variables That Don't Suck - Writing Clean Java Code
Python Tutorial for Beginners 2: Strings - Working with Textual Data
React Naming Conventions You should follow as a Junior Developer - clean-code
Excel VBA Programming - Variables and Data Types | 1 - Syntax Tips
5.0 / 5 (0 votes)