2  Running Python

One of the defining characteristics of Python is that it is an interpreted language. If you’ve used a language like Java or C you’re used to having to compile your code. Python is instead typically translated to an intermediate representation (bytecode) and immediately executed without a separate compilation step.

To do this, we need a Python interpreter, a program called python (sometimes python3).

There are many ways to install & manage Python and packages. We will be using uv, a relatively new entrant that has quickly become the preferred tool of a large portion of the Python community.

WarningConda Warning

If you have already installed Python via conda/miniconda, you may need to uninstall it to get some things to work properly.

While most Python tools are mostly compatible, Conda does not follow the standards that these tools have adopted.

You are free to try to proceed without uninstalling, but if you run into issues see Paul Romer’s Escaping from Anaconda on why and how.

WarningWindows Users

If you are a Windows user, we strongly recommend using WSL to have a Linux environment on your machine.

TAs and I are used to working in a Unix-like environment as provided by MacOS, Linux, or WSL on Windows. Many commands that work on all three of these will not work in Windows Powershell.

Due to the vast number of possible configurations, course staff are not able to offer technical support for Windows-specific issues and can only offer limited support for machine-specific issues regardless of platform.

Installing uv

  1. Go to this page, and follow the instructions for your environment: installing uv.
  2. Once uv is installed, type uv python install 3.14 in your terminal.
  3. After Python is installed, verify the version with uv run python -V. You should see a version that starts with 3.14.

Using uv

For this course, every assignment will come with uv configuration files (e.g. pyproject.toml and uv.lock).

These files specify any dependencies (third-party tools and libraries) that our given project depends upon.

By having these files exist on a per-project basis, different projects can use different tools (and versions of tools), and we do not need to worry about incompatabilities between say, the version of Pandas used in a PA for this course and for a project you’re using at work.

(Behind the scenes, uv is managing a virtual environment for you, replacing virtualenv, pip, poetry, and pdm if you are familiar with those tools.)

uv sync

If you are working on a new project that already has a pyproject.toml, the first command you’ll want to run is uv sync.

This creates a virtual environment (in hidden directory .venv) and installs the appropriate dependencies.

You will also see this create/modify a uv.lock file. This file ensures you can run the same code on multiple machines using the exact same versions of dependencies.

For example:

course/$ git clone git@github.com:jamesturk/assignment1.git
course/$ cd assignment1
course/assignment1/$ uv sync
Resolved 24 packages in 0.97ms
Audited 14 packages in 0.11ms

uv run <command>

To run commands using the installed dependencies, you must:

  1. Be inside the directory where uv sync was previously run.
  2. Prefix those commands with uv run

So pytest becomes uv run pytest. Some common commands:

  • uv run pytest - Run tests.
  • uv run python file.py - Execute a specified python file.
  • uv run ipython - Run an interactive REPL with access to all dependencies.

uv add / uv remove

These commands add and remove dependencies, they will both update your pyproject.toml, uv.lock, and local environment.

If you see a library that gives an instruction like: pip install django

You would instead write: uv add django

For the most part you will not need to use this, but in later assignments where you are given the option to use different libraries, you might. Be sure to commit the changes to pyproject.toml and uv.lock!

uv remove will do the opposite: the equivalent of pip uninstall or poetry add, etc.

After reading this you may decide to dive deeper with the uv docs.

Why uv?

If you have used Python before you may wonder why we’re adopting uv instead of older tools like pip, conda, or virtualenv.

Compared with those tools, it offers some distinct advantages:

  • It uses Python-standard conventions, such as installing packages from PyPI and using a pyproject.toml file.1
  • It allows installing Python, python packages, and eases developing locally with a single tool.2
  • It is signficantly faster than most alternatives.
  • It has quickly become a favored tool among long-time Python developers.3

Of course, you will need to use other tools in other classes, but that is par for the course in our field.

The Python REPL

One of the benefits of an interpreted language is that it is possible to run it one line at a time, in an interactive session.

uv run python

This feature of most interpreted languages is called a REPL (pronounced rep-el).

REPL stands for:

  • Read - takes user input, typically one line at a time
  • Evaluate - evaluate user input, running the code in the current context
  • Print - print the output of the evaluation automatically (without the need for a print())
  • Loop - repeat, until the user quits

This is incredibly useful, many Python programmers keep a REPL open at all times, to try out ideas / test things / look up documentation.

Exercise: python-demos directory

Let’s set up a small local Python project using uv so that we can try a different REPL and run some code together.

  1. Open a terminal and navigate (using cd) to a location where you’d like to create our demo repository.
  2. Make a new directory (mkdir python-demos) and then enter it (cd python-demos).
  3. Initialize the directory as a uv project with uv init.

This will create a pyproject.toml and some other files that aren’t needed for our purposes.

pyproject.toml exists at the root of a Python project and configures what other packages are needed.

  1. Let’s install a package with uv, run uv add ipython

This will update your pyproject.toml and uv.lock files and install the package for use from within this directory.

  1. To use this new package you can type uv run ipython from within the python-demos directory, and you will see ipython.

We’ll talk more about package management and what this tool is doing later in the course.

ipython vs python

ipython is an enhanced REPL for Python. It is using the same version of Python you already installed, but providing a different interface.

It provides command history, syntax highlighting, and a handful of other useful features that make it many people’s preferred REPL. It is up to you which you prefer, both provide access to the same core language.

You will often see interactive Python prompts shown as:

>>> x = 4 * 3
>>> print(x)
12  

The lines that begin with >>> are the Python prompt, and lines without >>> indicating output.

In ipython input/output lines are marked with In[0] and Out[0] prefixes, but when showing interactive output I will stick to convention and use >>>.

Tip: Don’t use pip (or conda)

You will see instructions using tools other than uv, but it is best to stick to a single tool.

When you are looking at Python libraries, which we’ll discuss later, you will often see instructions which state you should run pip install foo.

When you see pip install foo you should use uv add foo instead.

conda install instructions can usually be translated to uv add as well.

These tools are older than uv and can easily leave your system in a broken state, where uv restricts installs to the directory you are working in.

PyPI

Much of Python’s early allure was due to its “batteries included” philosophy. When you install Python on your system, it comes with libraries you’ve been using already: datetime, math, csv, json, itertools, and collections to name a few. Collectively these make up the standard library. These can be imported on any Python installation without any additional setup. As long as we have the same version of Python, code that runs on your machine should run on mine if it sticks to these packages. Not every language has a robust standard library, languages like C and Rust take different approaches than Python.

This approach has its limits though:

  • The standard library is the “official” way to do something, but typically there needs to be room for experimentation with new ideas to get there.
  • Some things may never have a “right” way, people will always have different opinions for something as large as a web framework or game library.
  • Some packages need to evolve faster than the language’s year-long release cycle.
  • And of course the language can’t possibly include everything, so the standards for inclusion in the core language are high- which should come as a relief!

For this reason, we have PyPI, the Python Package Index.

This is where any developer can upload their Python code for others to use.

So if you upload a package named jellyfish, then people will be able to install your code, type import jellyfish, and start using it.

ImportantSecurity Warning!

Did that worry you?

Take a minute and think about the things that code can do when you run it on your system.

A poorly-written or malicious library could crash your system, steal your data, or do virtually anything a user with their hands on your keyboard could do.

A few years ago a malicious user uploaded a package named jel1yfish, with the intention of confusing people intending to install jellyfish. They attacked hundreds of similarly named packages where a letter like an l or O could be replaced with a 1 or 0. These typo-squatted packages intended to hijack developer machines to mine cryptocurrency.

This attack was thwarted fortunately, but other similar attacks are surely happening regularly.

PyPI is a wonderful thing, but be fully aware that the packages available are not vetted, and so you should stick to packages that are well-known (and check for typos!) where possible, and when installing a niche package, do at least a basic check that the package is authentic.

If in doubt:

  • look for signs of activity on GitHub/etc.: a popular library with dozens of tutorials is one thing – an obscure library only one person used may also be fine, but worth a bit of vetting
  • look at the source code!
  • ask someone!

PyPI today has nearly 600,000 packages. If you are looking for code to help you with something, there’s a good chance you’ll be able to find it.

If Python’s early success was driven by the built in packages, its success today is primarily because of the ecosystem around it.

Python is used in data science in large part because of packages like pandas and SciPy, in web development because of Django and Flask. These are among the most popular Python packages, despite not being part of the standard library.

That means if we want to use pygame to work on our new game, we need to download it, but what do we do with a bunch of .py files?

Bonus Tool: ruff

uv and PyPI can be used to install tools in addition to packages.

The first tool we’ll install is going to make your life a lot easier, and raise your grade too.

uv add ruff will install the ruff package, which also happens to be a command line application.

ruff is both a linter and an autoformatter.

Autoformatting with ruff format

If you read the official Python style guide PEP 8. The section on blank lines contains a lot of pedantic rules:

Avoid extraneous whitespace in the following situations:

  • Immediately inside parentheses, brackets or braces:
  • Between a trailing comma and a following close parenthesis:
  • Immediately before a comma, semicolon, or colon:
  • However, in a slice the colon acts like a binary operator, and should have equal amounts on either side (treating it as the operator with the lowest priority). In an extended slice, both colons must have the same amount of spacing applied. Exception: when a slice parameter is omitted, the space is omitted:
  • …

These rules definitely lead to more readable code, but can be frustrating to remember & follow.

Wait, aren’t computers supposed to make our lives easier?

Autoformatters can automatically repair these kinds of errors in your code.

As long as you have valid Python code, ruff format myfile.py will reformat the file in question ensuring it adheres to accepted style guidelines.

For example:

# bad1.py
import json,os,sys
import random    # unused import
from datetime   import datetime

def process_data(x,y,     z):
    a=x+y
    if(z=="test"):
         return a*2
    else:
        return    a

def calculate_stuff( items ):
    total=0
    for i in range(len(items)):   # should use enumerate
        total+=items[i]
    

    return total

result = process_data(1,2,"test")
print(result)

After ruff format:

import json, os, sys
import random  # unused import
from datetime import datetime


def process_data(x, y, z):
    a = x + y
    if z == "test":
        return a * 2
    else:
        return a


def calculate_stuff(items):
    total = 0
    for i in range(len(items)):  # should use enumerate
        total += items[i]

    return total

result = process_data(1, 2, "test")
print(result)

This tool is minimally configurable, since the point is for us to all have the same style.

That means in some esoteric cases it will format your code in a strange, but predictable way.

Some people find themselves fighting it at first, but once you realize how much time it can save you the occasional strangeness is worth cleaner code at no additional effort.

TipThis is not AI!

To head off any fears, this is not AI.

This does not in any way violate the academic honesty policy in this course (or any others I am aware of, but always check against an instructor’s syllabus or ask if in doubt).

While many teams are restricting or banning generative AI tools, linters and autoformatters are mandated on many teams and the majority of open source projects.

These tools are not rewriting your code, merely reformatting it. They are akin to a spell checker, the thought in the file is still 100% your own,

Linting via ruff check

Not every error is fixed by autoformatting, a linter can warn about things that you may need to fix yourself like unused imports and variables.

import json


def func(a, b, c):
    return a + b
$ uv run ruff check --select ARG --select F bad2.py
bad2.py:1:8: F401 [*] `json` imported but unused
  |
1 | import json
  |        ^^^^ F401
  |
  = help: Remove unused import: `json`

bad2.py:4:16: ARG001 Unused function argument: `c`
  |
4 | def func(a, b, c):
  |                ^ ARG001
5 |     return a + b
  |

Found 2 errors.
[*] 1 fixable with the `--fix` option.

Alternatives

Just like uv supplanted poetry, pdm, pip and others, there are many linters and autoformatters and others, there were many linters and autoformatters.

ruff’s main advantage is speed, and it incorporates the linter rules from dozens of other libraries, the most popular being flake8 and pylint.

Further Exploration


  1. Conda quite notably does not follow Python conventions, often leading to incompatibilities with other Python tools. It is also starting to monetize as of 2025.↩︎

  2. In the past, a combination of pyenv, pipx, poetry, and/or pdm was required to get the same functionality.↩︎

  3. See https://simonwillison.net/2024/Aug/20/uv-unified-python-packaging/ and https://andrich.me/2024/09/uv-i-am-somewhat-sold/ for more.↩︎