So let’s say you are starting to program in Python, and you want to know how to start. What do you need to do?
Virtual Environment
Well, the first thing you need to do is install a virtual environment. There are two ways to do this:
- Install Anaconda. This provides you with a virtual environment with one command, along with several other features.
- Setup a virtual environment
If you are brand new to Python, please use Anaconda. It has everything you need. You download the installer from their website and run it. Restart your terminal, you’re good to go.
Let’s say for whatever reason you don’t want to use Anaconda. You still need to run a virtual environment. To do this on Linux, run the following commands:
- Install virtual environment for your distribution. For Ubuntu (or really any Debian based Linux) the command is
sudo apt-get install virtualenv
. If you’re not using a Debian based distro, look it up online if you don’t know the name of your package manager. - In your home directory, create a virtual environment using the command
virtualenv linuxtest
(name it whatever you want) - Set the virtual environment to activate when you start your terminal paste
echo 'source ~/linuxtest/bin/activate' >>~/.bashrc
in your command line. - Type
source ~/.bashrc
in order to activate your changes.
That’s it! Restart your terminal. You will see (linuxtest)
before your username in your terminal, assuming you don’t have a custom terminal display. This means it worked.
If not, you either have customized your kernel at some point, or it didn’t work. If you type which python
you should see /home/YOUR_USERNAME/linuxtest/bin/python
. If you don’t see that, type sudo rm -r ~/linuxtest
and try again.
But what’s the point?
Linux uses Python as part of how the Operating system is built. Because of this, the package manager modifies your root python installation. It will download, remove, and update any package it needs to do in order to keep your linux working. If you start upgrading, downgrading, or installing new packages, the best thing that could happen to you is that a package you use will be modified. The worst thing that could happen is you might fundamentally change a package which your operating system needs, and you could break Linux!
Don’t let this happen to you. If you wouldn’t download and run random executable files with names like va5e%smr2-09sd.exe from random websites with terrible graphics, you should use a virtual environment. Don’t screw up your operating system.
If you would run va5e%smr2-09sd.exe, then please stop doing that.
Pip
Python has its own package manager called pip. This is how every python package is packaged and distributed. In your terminal window, if you want to install any package, lets use Pandas as an example, just type pip install pandas
into your command line.
That’s it.
If you aren’t using a virtual environment, start using a virtual environment.
If you are using python as root. Stop using python as root.
Update all packages
Now that you have used pip, what if you want to ensure all of your packages in you virtual environment are up to date? Well, for that I have a special alias on all of my machines which is alias pipupgrade='pip list --outdated --format=freeze | grep -v '\''^\-e'\'' | cut -d = -f 1 | xargs -n1 pip install -U
. Paste this into your command line. Any time you want to ensure your packages are up to date all you need to do is type pipupgrade
into your command line and you are all set.
Which version of Python should I use?
You should use the latest version of python in your virtual environment. You can get away with the version prior to the latest release. So right now that is python 3.10. If you’re using Python 3.9, no problem. You can even get away with Python 3.7 right now, because Python has had a 5 year support cycle for the last decade. Please check wikipedia to make sure the version of python you have installed is currently supported. That way you get the latest features, security updates, and practically all libraries will work on your machine.
Because you are using a virtual environment it doesn’t matter which Python version your operating system is using, you can use any version of Python supported by your operating system in your virtual environment, and that’s the interpreter you will be using when you run things from the terminal.
If your operating system can’t support a version of Python which still gets security updates, its time to update your operating system. For now, just use Ubuntu and upgrade to the latest LTS every October of an even numbered year.
You could even setup multiple environments if you want to test against different versions of Python. That’s up to you.
Pep 8. Who cares?
Python is a very opinionated language. It also uses spacing as part of how the programming language runs code. Because of this, its very important to make sure your code is written properly. Pep 8 is built into modern linters to make sure that your code will be legible, work the same way everywhere, and be consistent. Use it.
Once you have your virtual environment setup, Pip is working, your code is Pep 8 compliant, and you have a version of python which is currently supported running on your computer, write whatever you want. It will work on other modern Python environments, and you don’t have anything to worry about.
Don’t hide errors, fail fast, fail when necessary
If you are writing python code and you find something fails, don’t just hide it in a blank try except clause like the following:
try:
print('hello world')
except:
pass
This practice provides no useful debug information to your user. While print(‘hello world’) is an incredibly simple program, with more complex programs this can become a very real problem. This wastes the time of your users, it creates unstable projects, and it’s just disrespectful. If you user puts in an input which your package can’t read, fail the program, tell them what the problem is, and make it so they can fix the problem quickly.
There are times where a try: except: clause is useful. In that case, specify which types of errors are appropriate to pass on. Ideally write your code so instead of simply failing it gives useful feedback to your program which will be more stable.
Read good code
Writing code is the best way to learn how to write any language. But reading code is an important part of learning how to write a language so its legible. Go through some of the packages you download and try to understand why the library is written the way it does. Compare the structure of your code to the structure of frequently used libraries which are the heart of the language. If you understand how they are written, your own code will improve.
Hierarchy of loops
Python is not C. Python offers several major types of loops which allow you to loop through code. When I write code I write them in the following preference:
- result = [x**2 for x in original_list] Python has list comprehensions. The advantage to list comprehensions is that it is done in place, and it automatically saves to a variable in one line. If you were to do this as a for loop it would take a minimum of three lines, where each line is very short. Once you are used to list comprehensions, you will prefer them. They are everywhere in good code. Get used to them.
- for x in y: print(‘x’) If you can make it work in a for loop. Use a for loop. If you can write in a single line in under 120 characters, use a list comprehension. For loops have a build in stopping point, they will not go on forever. This means your code won’t look like its working when in fact it has crashed.
- if x % 2: print(‘even’) else: print(‘odd’) If you need to do one thing under one condition, and another thing under another condition, use an if else loop.
- try: x except ValueError as error: raise error If you absolutely must use a try loop, make sure it prints the exception, except if there is a very good reason not to. If you can do it as a for loop, use a for loop.
- while x: print(time.now()) You probably don’t want to do this. You must be careful and build in a break statement. You probably just want to use a for loop. The advantage to a for loop is that if you miss the break condition the while loop will go on forever, with no error code. The for loop has a built in stopping point when the end of the list is reached. Only use this if every other option cannot be used.
This is my preference based on experience.
Write your own Pip package
You’ve been writing Python for a while now, you are comfortable with the language, and are writing complicated scripts. You might even have written something other people might want to use. Now is the time to do the next step in improving your Python journey, and improve your skills further. The best way to really solidify your python skills and solidify your understanding of the language is to write your own package for Pip. Follow the instructions at packaging.python.org step by step and install the wheel which is created at the end of your tutorial in a virtual environment. If it loads without errors, that means you can write code which is easy to read, and will run the same place everywhere.
There are many benefits to packaging your project and loading them as a library. Pip will tell you when major errors occur immediately. Pip will automagically make sure all dependencies are installed and give clear errors if they cannot be solved. It’s the easiest way to move your projects between different computers.
It helps you write better code.
Once you have mastered the basics, learn how to make a pip package.