Docsity

Python Best Practices: Avoiding Common Mistakes and Anti-Patterns, Notas de estudo de Engenharia Elétrica

Pré-visualização parcial do texto

Baixe Python Best Practices: Avoiding Common Mistakes and Anti-Patterns e outras Notas de estudo em PDF para Engenharia Elétrica, somente na Docsity!

How to

Make Mistakes

in Python

Mike Pirnat

Mike Pirnat

How to Make Mistakes

in Python

To my daughter, Claire, who enables me to see the world anew, and to my wife, Elizabeth, partner in the adventure of life.

    1. Setup. Introduction. xi
    • Polluting the System Python
    • Using the Default REPL
    1. Silly Things.
    • Forgetting to Return a Value
    • Misspellings
    • Mixing Up Def and Class
    1. Style.
    • Hungarian Notation
    • PEP-8 Violations
    • Bad Naming
    • Inscrutable Lambdas
    • Incomprehensible Comprehensions
    1. Structure.
    • Pathological If/Elif Blocks
    • Unnecessary Getters and Setters
    • Getting Wrapped Up in Decorators
    • Breaking the Law of Demeter
    • Overusing Private Attributes
    • God Objects and God Methods
    • Global State
    1. Surprises.
    • Importing Everything
    • Overbroadly Silencing Exceptions
    • Reinventing the Wheel
    • Mutable Keyword Argument Defaults
    • Overeager Code
    • Poisoning Persistent State
    • Assuming Logging Is Unnecessary
    • Assuming Tests Are Unnecessary
    1. Further Resources.
    • Philosophy
    • Tools

Introduction

To err is human; to really foul things up requires a computer. —Bill Vaughan

I started programming with Python in 2000, at the very tail end of The Bubble. In that time, I’ve…done things. Things I’m not proud of. Some of them simple, some of them profound, all with good intentions. Mistakes, as they say, have been made. Some have been costly, many of them embarrassing. By talking about them, by inves‐ tigating them, by peeling them back layer by layer, I hope to save you some of the toe-stubbing and face-palming that I’ve caused myself.

As I’ve reflected on the kinds of errors I’ve made as a Python pro‐ grammer, I’ve observed that they fall more or less into the categories that are presented here:

Setup How an incautiously prepared environment has hampered me.

Silly things The trivial mistakes that waste a disproportionate amount of my energy.

Style Poor stylistic decisions that impede readability.

Structure Assembling code in ways that make change more difficult.

xi

With any luck, after reading this you will be in a position to make a more interesting caliber of mistake: with an awareness of what can go wrong, and how to avoid it, you will be freed to make the excit‐ ing, messy, significant sorts of mistakes that push the art of pro‐ gramming, or the domain of your work, forward.

I’m eager to see what kind of trouble you’ll get up to.

Introduction | xiii

site-packages directory. Any time you fire up a Python shell or a Python program, you’ll be able to import and use that package.

That may feel okay at first, but once you start developing or working with multiple projects on that computer, you’re going to eventually have conflicts over package dependencies. Suppose project P depends on version 1.0 of library L, and project P2 uses version 4. of library L. If both projects have to be developed or deployed on the same machine, you’re practically guaranteed to have a bad day due to changes to the library’s interface or behavior; if both projects use the same site-packages, they cannot coexist! Even worse, on many Linux distributions, important system tooling is written in Python, so getting into this dependency management hell means you can break critical pieces of your OS.

The solution for this is to use so-called virtual environments. When you create a virtual environment (or “virtual env”), you have a sepa‐ rate Python environment outside of the system Python: the virtual environment has its own site-packages directory, but shares the standard library and whatever Python binary you pointed it at dur‐ ing creation. (You can even have some virtual environments using Python 2 and others using Python 3, if that’s what you need!)

For Python 2, you’ll need to install virtualenv by running pip install virtualenv, while Python 3 now includes the same func‐ tionality out-of-the-box.

To create a virtual environment in a new directory, all you need to do is run one command, though it will vary slightly based on your choice of OS (Unix-like versus Windows) and Python version (2 or 3). For Python 2, you’ll use:

virtualenv <directory_name>

while for Python 3, on Unix-like systems it’s:

pyvenv <directory_name>

and for Python 3 on Windows:

pyvenv.py <directory_name>

2 | Chapter 1: Setup

Windows users will also need to adjust their PATH to include the location of their system Python and its scripts; this procedure varies slightly between versions of Windows, and the exact setting depends on the ver‐ sion of Python. For a standard installation of Python 3.4, for example, the PATH should include: C:\Python34;C:\Python34\Scripts;C: \Python34\Tools\Scripts

This creates a new directory with everything the virtual environ‐ ment needs: lib (Lib on Windows) and include subdirectories for supporting library files, and a bin subdirectory (Scripts on Win‐ dows) with scripts to manage the virtual environment and a sym‐ bolic link to the appropriate Python binary. It also installs the pip and setuptools modules in the virtual environment so that you can easily install additional packages.

Once the virtual environment has been created, you’ll need to navi‐ gate into that directory and “activate” the virtual environment by running a small shell script. This script tweaks the environment variables necessary to use the virtual environment’s Python and site-packages. If you use the Bash shell, you’ll run:

source bin/activate

Windows users will run:

Scripts\activate.bat

Equivalents are also provided for the Csh and Fish shells on Unix- like systems, as well as PowerShell on Windows. Once activated, the virtual environment is isolated from your system Python—any packages you install are independent from the system Python as well as from other virtual environments.

When you are done working in that virtual environment, the deactivate command will revert to using the default Python again.

As you might guess, I used to think that all this virtual environment stuff was too many moving parts, way too complicated, and I would never need to use it. After causing myself significant amounts of pain, I’ve changed my tune. Installing virtualenv for working with Python 2 code is now one of the first things I do on a new computer.

Polluting the System Python | 3

Up arrow. Up. Up. Up. Up. Enter.

Up. Up. Up. Up. Up. Enter. Up. Up. Up. Up. Up. Enter. Up. Up. Up. Up. Up. Enter.

Up. Up. Up. Up. Up. Enter. Then I get the same SyntaxError because I got into a rhythm and pressed Enter without fixing the error first. Whoops!

Then I repeat this cycle several times, each iteration punctuated with increasingly sour cursing.

Eventually I’ll get it right, then realize I need to add some more things to the init, and have to re-create the entire class again, and then again, and again, and oh, the regrets I will feel for having reached for the wrong tool out of my old, hard-to-shed habits. If I’d been working with the Jupyter Notebook, I’d just change the error directly in the cell containing the code, without any up-arrow she‐ nanigans, and be on my way in seconds (see Figure 1-1).

Figure 1-1. The Jupyter Notebook gives your browser super powers!

Using the Default REPL | 5

It takes just a little bit of extra effort and forethought to install and learn your way around one of these more sophisticated REPLs, but the sooner you do, the happier you’ll be.

6 | Chapter 1: Setup