pythonic way of
writing programs:
The Best way to use python
-
What to do
-
what to avoid
-
how to strike the right balance
-
why this is the best choice
pythonic thinking
Python programmers prefer to be explicit, to choose simple over complex, and to maximize readability.
The Best Way to do the most common things in python
pythonic thinking
Know Which Version of Python You're Using
pythonic thinking
Know Which Version of Python You're Using
- Development on Python 2 is frozen beyond bug fixes, security improvements and backreports to ease the transition from Python 2 to Python 3.
- Python 3 is constantly getting new features and improvements.
- The majority of Python's most common open source libraries are compatible with Python 3
It's strongly recommended to use Python 3 in their next projects
pythonic thinking
follow the pep 8 style guide
The style guide for how to format Python code
- Code more approachable and easier to read.
- Facilitates collaboration on projects.
- Make it easier to change things later.
pythonic thinking
follow the pep 8 style guide
PEP 8 has a wealth of details about how to write clear python code.
Here are few rules you should be sure to follow:
Whitespace:
- Use spaces instead of tabs for indentation.
- Use four spaces for each level of syntactically significant indenting.
- Lines should be 79 characters in length or less.
- In a file, functions and classes should be separated by two blank lines.
- In a class, methods should be separated by one blank line.
- Put one - and only one - space before and after variable assignments
pythonic thinking
follow the pep 8 style guide
Naming:
- Functions, variables, and attributes should be in lowercase_underscore format.
- Protected instance attributes should be in _leading_underscore format.
- Private instance attributes should be in __double_leading_underscore format.
- Classes and exceptions should be in CapitalizeWord format.
- Instance methods in classes should use self as the name of the first parameter.
- Class methods should use cls as the name of the first parameter.
pythonic thinking
follow the pep 8 style guide
Expressions and Statements:
- Use inline negation (if a is not b) instead of negation of positive expressions (if not a is b).
- Don't check for empty values (like [] or ' ') by checking the length (if len(somelist) == 0). Use if not somelist.
- Avoid single-line if statements, for and while loops. Spread these over multiple lines for clarity.
- Always put import statements at the top of a file.
- If you must do relative imports, use the explicit syntax.
- Imports should be in sections in the following order: standard library modules, third-party modules, your own modules. Each subsection should have imports in alphabetical order.
pythonic thinking
follow the pep 8 style guide
Things to Remember:
- Always follow the PEP 8 style guide when writing Python code.
- Sharing a common style with the larger Python community facilitates collaboration with others.
- Using a consistent style makes it easier to modifiy your own code later.
pythonic thinking
know the differences between bytes, str and unicode
In Python 3, there are two types that represent sequences of characters:
bytes = 8-bit values
str = Unicode characters
In Python 2, there are two types that represent sequences of characters:
str = 8-bit values
unicode = Unicode characters
pythonic thinking
know the differences between bytes, str and unicode
There are may ways to represent Unicode characters as binary data (raw 8-bit values). The most common encoding is UTF-8.
Importantly, str instances in Python 3 and unicode instances in Python 2 do not have an associated binary encoding.
When you're writing Python programs, it's important to do encoding and decoding of Unicode at the furthest boundary of your interfaces.
The core of your program should use Unicode character types (str in Python 3, unicode in Python 2)
pythonic thinking
know the differences between bytes, str and unicode
The slip between character types leads to two common situations in Python code:
- You want to operate on raw 8-bit values that are UTF-8-encoded character (or some other encoding).
- You want to operate on Unicode characters that have no specific encoding.
You'll often need two helper functions to convert between these two cases and to ensure that the type of input values matches your code's expectations.
pythonic thinking
know the differences between bytes, str and unicode
Python 3:
pythonic thinking
know the differences between bytes, str and unicode
Python 2:
pythonic thinking
know the differences between bytes, str and unicode
Things to Remember:
- In Python 2, str contains sequences of 8-bit values, unicode contains sequences of Unicode characters, str and unicode can be used together with operators (like > or +)
- In Python 3, bytes contains sequences of 8-bit values, str contains squences of Unicode characters. bytes and str instances can't be used together with operators.
- Use helper functions to ensure that the inputs you operate on are the type of character sequence you expect (8-bit values, UTF-8 encoded characters, Unicode characters, etc).
pythonic thinking
know how to slice sequences
Python includes syntax for slicing sequences into pieces. Slicing lets you access a subset of a sequence's items with minimal effort.
The basic form of the slicing syntax is somelist[start:end]. Where start is inclusive and end is exclusive.
pythonic thinking
know how to slice sequences
Using negative numbers for slicing is helpful for doing offsets relative to the end of a list.
pythonic thinking
know how to slice sequences
The result of slicing a list is a whole new list. References to the objects from the original list are maintained. Modifying the result of slicing won't affect the original list.
pythonic thinking
know how to slice sequences
When used in assignments, slices will replace the specified range in the original list.
The list will grow or shrink to accommodate the new values
pythonic thinking
know how to slice sequences
If you leave out both the start and the end indexes when slicing, you'll end up with a copy of the original list.
pythonic thinking
know how to slice sequences
If you assign a slice with no start or end indexes, you'll replace its entire contents with a copy of what's referenced (instead of allocating a new list)
pythonic thinking
know how to slice sequences
- Avoid being verbose: Don't supply 0 for the start index or the length of the sequence for the end index.
- Slicing is forgiving of start or end indexes that are out of bounds, making it easy to express slices on the front or back boundaries of a sequence (like a[:20] or a[-20:].
- Assigning to a list slice will replace that range in the original sequence with what's referenced even if their lengths are different.
Things to Remember:
pythonic thinking
use list comprehensions instead of map and filter
Python provides compact syntax for deriving one list from another.
These expressions are called list comprehensions.
Is visually noisy
pythonic thinking
use list comprehensions instead of map and filter
List comprehensions let you easily filter items from the input list, removing corresponding outputs from the result.
It is much harder to read
pythonic thinking
use list comprehensions instead of map and filter
Things to Remember:
- List comprehensions are clearer than the map and filter built-in functions because they don't require extra lambda expressions.
- List comprehensions allow you to easily skip items from the input list, a behavior map doesn't support without help from filter.
pythonic thinking
prefer enumerate over range
When you have a data structure to iterate over, like a list of strings, you can loop directly over the sequence.
pythonic thinking
prefer enumerate over range
You'll want to iterate over a list and also know the index of the current item in the list.
pythonic thinking
prefer enumerate over range
Python provides the enumerate built-in function for addressing this situation. enumerate wraps any iterator with a lazy generator. This generator yields pairs of the loop index and the next value from the iterator.
pythonic thinking
prefer enumerate over range
Things to Remember:
- enumerator provides concise syntax for looping over an iterator and getting the index of each item from the iterator as you go.
- Prefer enumerate instead of looping over a range and indexing into a sequence.
pythonic thinking
take advantage of each block in try/except/else/finally
There are four distinct times that you may want to take action during exception handling in Python. These are captured in the functionality of try, except, else and finally blocks.
Finally Blocks
Use try/finally when you want exceptions to propagate up, but you also want to run cleanup code even when exceptions occur.
pythonic thinking
take advantage of each block in try/except/else/finally
Else Blocks
Use try/except/else to make it clear which exceptions will be handled by your code and which exceptions will propagate up. When the try block doesn't raise an exception, the else block will run.
pythonic thinking
take advantage of each block in try/except/else/finally
Everything Together
pythonic thinking
take advantage of each block in try/except/else/finally
Things to Remember
- The try/finally compound statement lets you run cleanup code regardless of whether exceptions were raised in the try block.
- The else block helps you minimize the amount of code in try blocks and visually distinguish the success case from the try/except blocks.
- An else block can be used to perform additional actions after a successful try block but before common cleanup in a finally block.
pythonic thinking
Thanks !
deck
By Juan David Hernández Giraldo
deck
- 754