Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

The Programming Shortcut: Python

Part of The Programming Shortcut, a series that teaches one programming idea per article to people who already program. This one is about standing on libraries, and duck typing.

Most of your program is already written

Python is a language for getting things done, and it gets them done by letting you borrow.

When you write a Python program that renames a folder of photos, or totals a spreadsheet, or checks which of your files are copies of each other, you write perhaps thirty lines. Underneath those thirty lines sit many thousands more that somebody else wrote, tested and documented, and that came with Python when you installed it. Python’s own people call this “batteries included.” The standard library, the collection of ready-made code that ships with the language, is enormous, and it’s the reason a beginner’s Python script can do things that would take days in a language without one.

The new idea in this article is the skill that goes with it: standing on libraries. Using code you didn’t write, written by people who never met you, for problems they had never seen. And the trick that makes it work in Python is called duck typing, which sounds silly and is one of the most useful ideas in programming.

You won’t learn much Python syntax here. You’ll learn how to plug your code into somebody else’s, and why it fits.

What you already know, in Python

Python spells the familiar things like this:

What you knowluxPython
a functionfunc area(w: int) -> int { … }def area(w):
a block of codebraces { … }indentation: the lines indented under the :
a recordstructa class marked @dataclass
a value that might be missingOptionNone
errors you expectResultexceptions
a lookup table from keys to valuesnone: you build onedict: {"cat": 2, "mat": 1}
code someone else wrotenone beyond the built-insimport
when types are checkedbefore running, every branchnever by the language

Variables, conditionals, loops, lists and recursion all work the way you expect, so this article will use them without comment. Indentation is the one surprise: Python has no braces, and the indentation is the block. Your editor will help.

Two rows deserve a pointer. Exceptions are errors that jump out of a function instead of being returned from it, and Java is where this series explains them. “When types are checked” is the question the introduction asks of every language, and Python’s answer turns out to matter a lot below.

Edit, then run

Python needs one tool: the python3 command, plus any text editor you like. If you don’t have Python yet, the installers are at python.org/downloads. Most Linux systems already have it; type python3 --version in a terminal to find out.

The commands in this article are written for a macOS or Linux terminal. On Windows, the Python install manager gives you a py command; type py wherever this article says python3 (the details are in Using Python on Windows).

Make a file called hello.py:

name = "library"
print("Hello,", name)

Then run it:

python3 hello.py

It prints Hello, library. From here on: edit the file, save it, run it again. There’s no compile step to wait for. Python reads your file and runs it, top to bottom.

Keep that file open. You’re about to borrow something.

Someone already wrote that

Suppose you want to know which words turn up most in a piece of text. You know how to do this. Make a lookup table, walk the words, add one each time:

text = "the cat sat on the mat and the cat slept"

counts = {}
for word in text.split():
    counts[word] = counts.get(word, 0) + 1

print(counts)

That works, and you could take it further: sort the table by count, pick the top two. Ten minutes of careful work, maybe less.

Or you could notice that counting things is a problem every programmer has had, and that somebody has solved it already. Replace the contents of hello.py with this and run it:

from collections import Counter

text = "the cat sat on the mat and the cat slept"
print(Counter(text.split()).most_common(2))

It prints [('the', 3), ('cat', 2)]: the two most common words, with their counts, most common first. One line did what your loop did, plus the sorting you hadn’t written yet.

That first line is the new part. collections is a module: a file of Python code, usually written by somebody else, that your program can use. Counter is one of the things defined in it. from collections import Counter means “go and find the collections module, and let me use its Counter here.”

This is the habit this article is about, in miniature. Before you write the loop, ask: has someone already written this? In Python, for ordinary problems (dates, files, text, numbers, the web), the answer is usually yes, and it’s usually already on your disk.

A module is just a file

import can feel like magic, so take the magic away. Ask a module where it lives:

import random

print(random.__file__)

On a Linux machine with Python 3.13 that prints something like /usr/lib/python3.13/random.py. It’s a plain text file, in the same language you’re writing, sitting on your own disk. You could open it in your editor right now and read how Python picks random numbers. (Look, but don’t change it: every Python program on your machine uses that file.)

When you write import random, Python finds that file, runs it once, and gives you one name, random, that holds everything the file defined. You reach inside with a dot: random.choice(["heads", "tails"]). That name is a namespace, a container that keeps the module’s names apart from yours, so its choice doesn’t collide with any choice you might write yourself.

And because a module is just a file, you can make one. Put this in a file called greet.py:

def hello(name):
    return "Hello, " + name + "!"

Then, in another file in the same folder:

import greet

print(greet.hello("Ada"))

Run the second file and it prints Hello, Ada!. Nothing about greet.py is special. The modules that ship with Python are files like it, only written by people with more time and more tests.

Reading the label

Using someone else’s code well comes down to one skill: reading the label. You don’t need to know how Counter works inside. You need to know what it wants from you and what it gives back.

Python keeps that label with the code. Every module, class and function carries its own documentation, and the help function prints it. Add help(Counter.most_common) to a script, or type it into Python’s interactive prompt (more on that at the end), and it tells you what most_common takes and returns. The same text, with examples, is in the library reference, which is worth skimming once just to see how much is in there.

Now look closely at what Counter wants, because this is where Python gets interesting.

If it quacks like a duck

Counter(text.split()) gave Counter a list of words. What else will it take?

from collections import Counter

print(Counter("banana"))
print(Counter(["red", "blue", "red"]))
print(Counter(range(3)))

A string, and it counts letters. A list, and it counts the items. A range, and it counts numbers. Counter was written once, by someone who had never seen your program, and it works on all three.

How? Counter never asks what type of thing you gave it. It only does one thing with it: it loops over it, taking items one at a time. Anything that can be looped over works. Python’s word for “something you can loop over” is an iterable, and the documentation for Counter says it counts elements “from an iterable.” It doesn’t say “from a list.”

That’s duck typing. The name comes from an old saying: if it looks like a duck and quacks like a duck, it’s a duck. Python’s version is more practical: if it can do what I’m about to ask of it, I don’t care what it is. A function written in this style doesn’t check the type of what it’s given. It calls the methods it needs and trusts them to be there.

In lux, every function names its parameter’s type, text: string, and lux holds you to it before the program runs. A Python library makes a looser promise: give me anything that can do this, and I’ll work.

Plugging your own code in

Duck typing works in both directions, and the second direction is the powerful one. It isn’t only that a library accepts many of Python’s types. It accepts yours too, as long as yours can quack.

Here’s a library function you have used since your first program. Run help(print) and part of what it says is:

file
  a file-like object (stream); defaults to the current sys.stdout.

print writes to the screen by default, but you can hand it somewhere else to write. A file-like object is anything that behaves like an open file. And what does print actually do with that object? It calls one method on it: write, with the text to write. That’s the duck. Anything with a write method quacks.

So make one. A class is a way to define your own kind of object along with the functions that belong to it, which are called methods. This one has a single method, write, that shouts whatever it’s given:

import sys
import json

class Shouter:
    def write(self, text):
        sys.stdout.write(text.upper())

loud = Shouter()
print("hello from print", file=loud)
json.dump({"name": "Ada", "langs": ["lux", "python"]}, loud)
print()

(self is how a method refers to the object it belongs to. You can ignore it here. sys.stdout is the screen, as a file-like object.)

Run it:

HELLO FROM PRINT
{"NAME": "ADA", "LANGS": ["LUX", "PYTHON"]}

Two libraries that know nothing about Shouter just used it. print sent it a line of text. json.dump, which turns Python data into JSON (JavaScript Object Notation, the text format most of the web uses to swap data), sent it a JSON document in pieces. Neither checked what loud was. Each called write, and write was there.

The documentation for json.dump describes what it wants as “a .write()-supporting file-like object.” Read that phrase again. It doesn’t name a type at all. It names a behavior. That phrase, or one like it, turns up all over Python’s documentation.

This is why standing on libraries in Python feels so easy. Library authors write against behaviors, not types, so the pieces fit together without anyone planning for it. A function that writes to the screen can write to a file, or to memory, or to a network connection, or to something you invented five minutes ago, because all of them answer to write.

Other languages reach the same goal by writing the agreement down. A Swift protocol is a named list of methods a type promises to have, and the compiler checks the promise before anything runs; Swift is where this series teaches it. Python makes the same arrangement with nothing written down at all.

When the duck doesn’t quack

So what happens when you hand a library something that can’t do what it asks?

import json

class Mute:
    pass

json.dump({"name": "Ada"}, Mute())

Mute has no methods at all. Save it as mute.py, run it, and Python stops:

Traceback (most recent call last):
  File "/home/you/mute.py", line 6, in <module>
    json.dump({"name": "Ada"}, Mute())
    ~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/lib/python3.13/json/__init__.py", line 180, in dump
    fp.write(chunk)
    ^^^^^^^^
AttributeError: 'Mute' object has no attribute 'write'

That report is a traceback: the chain of function calls Python was in the middle of when it stopped, oldest at the top, newest at the bottom. Read it from the bottom up. The last line is what went wrong: something tried to call write on a Mute, and there was no write. The line above it says where: inside the json library’s own file, at the moment it tried to quack your duck. One step further up is your line, the call that handed the library the wrong thing.

Notice when this happened. Python didn’t look at Mute when you defined it, or when you passed it to json.dump. It found out at the last possible moment, when the library reached for a method that wasn’t there. If that call had been inside an if that didn’t run, you wouldn’t have heard about it. That’s Python’s answer to the introduction’s question: the language itself never checks types ahead of time. It just tries.

What you give up

Duck typing is generous, and the price of generosity is that nobody writes the agreement down.

In a language that checks types before running, the agreement between your code and a library is part of the program. If you hand a function the wrong thing, you hear about it before anything runs, at the line where you made the mistake. In Python the agreement lives in documentation and in the library’s habits. You learn it by reading the label, and if you read it wrong you learn it from a traceback, at runtime, in a file you didn’t write.

That has two practical consequences. First, test the branches you care about, because nothing else will look at them. Second, when a traceback ends inside a library, don’t assume the library is broken. Walk up the traceback until you reach a line of yours: that’s almost always where the mistake is.

If you want the agreement written down, Python lets you add it. Type hints, like def hello(name: str) -> str, record what a function expects, and a separate checker such as mypy reads them before you run anything. The language itself ignores them. That idea, static checking as a tool you choose, gets its own article: TypeScript.

There’s one more thing you give up, and it applies to every language with libraries: when you import someone’s code, it runs on your machine with all of your permissions, and its bugs become your bugs. The standard library is about as trustworthy as code gets. Code from strangers on the internet deserves a little more reading before you stand on it.

Beware of the packaging-tool debate. The standard library goes a long way, but eventually you’ll want something it doesn’t have, and you’ll find out that the wider Python world installs third-party code with a crowd of competing tools, each with fans who will tell you the others are wrong. Pick one and ignore the rest. My advice is the pair that ships with Python itself: python3 -m venv to make a virtual environment (a private folder of libraries for one project, so projects can’t break each other) and pip inside it to install what you need. It isn’t the fanciest option, and it works everywhere Python does. Many Linux systems now refuse to let pip install into the system’s own Python at all, which is that same advice enforced. And before you install anything, check the standard library first. You’ll be surprised how often the battery was already in the box.

The project: find your duplicate files

Every computer collects duplicates: the photo you downloaded twice, the backup of a backup. Finding them by hand is tedious. Finding them with Python takes about fifty lines, and most of the work is done by four modules you don’t have to write.

Here’s the plan. Two files are duplicates if they have the same contents. Comparing every file with every other file would be slow, so first group files by size (files of different sizes can’t match), and only for sizes shared by two or more files, compute a fingerprint of the contents. A fingerprint here is a hash: a short string computed from a file’s bytes, which changes completely if even one byte changes. Files with the same hash have the same contents.

Make a folder for the project, and in it a file called dupes.py:

import sys
from collections import defaultdict
from hashlib import file_digest
from pathlib import Path


def fingerprint(path):
    with path.open("rb") as f:
        return file_digest(f, "sha256").hexdigest()


def find_duplicates(folder):
    by_size = defaultdict(list)
    for path in Path(folder).rglob("*"):
        if path.is_file():
            by_size[path.stat().st_size].append(path)

    by_content = defaultdict(list)
    for paths in by_size.values():
        if len(paths) > 1:
            for path in paths:
                by_content[fingerprint(path)].append(path)

    groups = [paths for paths in by_content.values() if len(paths) > 1]
    return sorted(groups, key=wasted_bytes, reverse=True)


def wasted_bytes(paths):
    return paths[0].stat().st_size * (len(paths) - 1)


def report(groups, out):
    if not groups:
        print("No duplicates found.", file=out)
    for paths in groups:
        print(f"{len(paths)} copies, {wasted_bytes(paths):,} bytes to reclaim:", file=out)
        for path in sorted(paths):
            print("   ", path, file=out)


def main():
    if len(sys.argv) < 2:
        sys.exit("usage: python3 dupes.py FOLDER [REPORT-FILE]")
    groups = find_duplicates(sys.argv[1])
    if len(sys.argv) > 2:
        with open(sys.argv[2], "w") as out:
            report(groups, out)
        print(f"Wrote {len(groups)} groups to {sys.argv[2]}")
    else:
        report(groups, sys.stdout)


main()

The full file, with a “Try this next…” list at the end, is in projects/python/dupes.py.

Read it for what it borrows, because that’s most of it:

pathlib.Path knows about folders and files. rglob("*") walks a folder and every folder inside it, handing back each path it finds. You didn’t write a recursive folder walk.

collections.defaultdict(list) is a lookup table that starts every new key with an empty list, so by_size[size].append(path) works the first time a size turns up. You didn’t write “if this key isn’t there yet, add it.”

hashlib.file_digest computes the SHA-256 hash (one well-known recipe for fingerprints) of a file. Its documentation says it wants “a file-like object opened for reading in binary mode.” That’s a duck again: it doesn’t care what f is, only that it behaves like a file opened for binary reading.

sys.argv is the list of words typed on the command line, and sys.stdout is the screen.

sorted is built in, and it’s a duck-typed function you’ve been using all along: it takes anything iterable and hands back a sorted list. Its key argument names a function, here wasted_bytes, that says what to sort by.

Two small pieces of Python syntax turn up too. The square brackets in [paths for paths in ... if len(paths) > 1] build a list from a loop and a condition in one line; it’s the loop you’d write anyway, folded up. And an f before a string, as in f"{len(paths)} copies", fills in each {…} with the value inside it.

And there’s one more duck, the one you wrote. report takes an argument called out and only ever passes it to print(..., file=out). In main, it gets the screen when you don’t name a report file, and a real open file when you do. The report function doesn’t know or care which. It’s the Shouter trick, put to work.

There’s also a library call disguised as a keyword. with open(...) as out: opens a file and guarantees it gets closed when the indented block ends, even if something goes wrong inside.

Run it on a folder that’s likely to have copies in it, such as your downloads:

python3 dupes.py ~/Downloads

You’ll see each group of identical files, the largest wasted space first. Here’s what it printed for a small test folder called photos:

3 copies, 100,000 bytes to reclaim:
    photos/big.bin
    photos/big2.bin
    photos/old/big-backup.bin
2 copies, 10 bytes to reclaim:
    photos/beach.jpg
    photos/old/beach-copy.jpg

Your own folder will give different results, of course, and if you’re tidier than most you’ll see No duplicates found. Copy a file or two into the folder and run it again. Now name a report file, and the same report function writes there instead:

python3 dupes.py ~/Downloads dupes.txt

The script only reports. It never deletes anything, which is the right first version of any program that looks at your files.

What’s left out, and where to go next

This article skipped most of what Python can do, because the idea was to learn how to borrow, not what to borrow. It left out classes beyond the two tiny ones you made, and the dunder methods (“double underscore,” with names like __len__ and __iter__) that let your own classes quack like Python’s built-in types. It left out typing.Protocol, Python’s way of writing a duck down so a checker can hold you to it. It left out packages from outside the standard library, virtual environments beyond one sentence, and the long, mostly settled story of Python 2. And it left out the more cautious style of duck typing, where code asks whether something has a method before calling it.

When you want more, go to the people who make the language. The official Python tutorial is clear and complete, and the library reference is the catalog of everything that came in the box. Its contents page alone will give you ideas for programs to write.

One last thing to try

Type python3 on its own, with no file. You get Python’s REPL (read, evaluate, print, loop): a prompt where you type one line, Python runs it, and shows you the result.

At the >>> prompt, type import this. Python prints its own philosophy, The Zen of Python, in nineteen short lines. Some of it will make more sense after this article than before.

Then bring it a question. Type import json, then help(json.dump), and find the words that describe fp. Does it ask for a type, or for a behavior? Now pick any library function you’re curious about and ask help the same thing: what does this need from me? Type q to leave the help page and exit() to leave the REPL.

  • Swift: protocols, the same agreement as duck typing, written down and checked before running.
  • TypeScript: static checking as a tool you choose, the approach Python’s type hints and mypy take.
  • Java: exceptions, Python’s way of reporting errors.

Tested with Python 3.13.5, November 2026.