Advanced   Chapter 186 · 45 min read · Module 14: Advanced Application Development

Python Application Development

Learning objectives
  • After this chapter you can plan an application and split it into interface, logic and storage.
  • You can model data with dataclasses and save it to JSON files with pathlib.
  • You can build a command-line interface with argparse.
  • You can use logging and custom exceptions for clear messages and errors.
  • You can write unit tests and use a main guard, a virtual environment and a requirements file.

Writing a ten-line script is easy. Writing a program that others use, that grows over time, and that you can still understand next year is a different job. That job is application development, and Python is a very good language for it.

In this chapter you will build the habits that make programs maintainable. You will separate the parts of a program, describe data with dataclasses, keep data in files, accept options from the command line, report what is happening with logging, and prove your code works with tests.

Everything here uses the standard library, so you can try each idea right away without installing anything. The same ideas apply when you later use frameworks such as Flask, Django or FastAPI.

From scripts to applications

A script is a file you run once to do one job. An application is a program that other people use, that has several parts, and that you must keep working for months or years. The Python you already know is enough to build applications, but you need some extra habits: split the code into small pieces, handle input and errors with care, keep settings outside the code, write tests, and make the program easy to run. This chapter walks through those habits using only the standard library.

Plan the structure

Before you write code, decide what the program does and break it into parts. A common layout separates the user interface (reading input, printing results) from the logic (the rules of the program) and from storage (files or a database). When logic lives in plain functions that take values and return values, you can test it without typing anything. A small project might look like this:

Typical project layout
todo_app/
  todo/
    __init__.py
    models.py      # data classes
    storage.py     # load and save JSON
    cli.py         # argparse and printing
  tests/
    test_models.py
  README.md
  pyproject.toml
(folder tree, not executed)

Model the data with dataclasses

A dataclass is a short way to write a class that mostly stores data. Python writes __init__, __repr__ and __eq__ for you from the field list. Give fields type hints and defaults. Use field(default_factory=list) for a mutable default so that objects do not share one list. Put the rules of the program in small methods of the class or in plain functions.

Example 1: a data model with a method
from dataclasses import dataclass, field

@dataclass
class Task:
    title: str
    done: bool = False
    tags: list = field(default_factory=list)

    def mark_done(self):
        self.done = True

task = Task("Buy milk", tags=["home"])
print(task)
task.mark_done()
print(task.done)
print(task == Task("Buy milk", True, ["home"]))
Task(title='Buy milk', done=False, tags=['home']) True True

Keep settings and data in files

Do not hard-code file names, limits or messages deep in the code. Keep them in one place, such as a settings dictionary or a JSON file, so you can change them without touching the logic. The json module turns dictionaries and lists into text and back. Always convert your objects to plain dictionaries before saving, and rebuild them when loading. Use pathlib.Path for file paths because it works the same on every operating system.

Example 2: save and load JSON
import json
from dataclasses import dataclass, asdict
from pathlib import Path

@dataclass
class Task:
    title: str
    done: bool = False

path = Path("tasks.json")
tasks = [Task("Read"), Task("Code", True)]
path.write_text(json.dumps([asdict(t) for t in tasks]), encoding="utf-8")

raw = json.loads(path.read_text(encoding="utf-8"))
loaded = [Task(**item) for item in raw]
print(loaded)
print(len(loaded))
[Task(title='Read', done=False), Task(title='Code', done=True)] 2

Command-line interfaces with argparse

Many applications are run from a terminal with options, for example todo add "Buy milk". The argparse module reads those arguments, checks them, builds the help text and shows clear error messages. You describe the arguments, then call parse_args(). For testing you can pass a list yourself, as shown below, instead of reading the real command line.

Example 3: parse arguments from a list
import argparse

parser = argparse.ArgumentParser(prog="todo")
parser.add_argument("command", choices=["add", "list"])
parser.add_argument("--title", default="")
parser.add_argument("--count", type=int, default=1)

args = parser.parse_args(["add", "--title", "Buy milk", "--count", "3"])
print(args.command, args.title, args.count + 1)
add Buy milk 4

Logging and error handling

print is for the result your user wants. For messages about what the program is doing, use the logging module. It has levels (DEBUG, INFO, WARNING, ERROR, CRITICAL), time stamps if you ask for them, and can send messages to the screen or a file. Pair it with try and except around risky actions such as reading a file, and catch specific exceptions rather than a bare except. Raise your own clear errors when the input is invalid, so mistakes are found early.

Example 4: logging and a custom error
import logging
import sys

logging.basicConfig(stream=sys.stdout, level=logging.INFO, format="%(levelname)s: %(message)s")
log = logging.getLogger("app")

class InvalidAge(ValueError):
    pass

def check_age(age):
    if age < 0:
        raise InvalidAge(f"age cannot be negative: {age}")
    return age

log.info("starting")
try:
    check_age(-5)
except InvalidAge as e:
    log.error("bad input (%s)", e)
log.debug("this line is hidden at INFO level")
INFO: starting ERROR: bad input (age cannot be negative: -5)

Test your code

Tests are small programs that check your functions. They let you change code with confidence. The standard library includes unittest, and the popular pytest package makes tests shorter. A test calls a function with known input and compares the result with the expected value. Write tests for normal cases, edge cases such as an empty list, and error cases.

Example 5: a unit test
import unittest

def average(values):
    if not values:
        raise ValueError("empty list")
    return sum(values) / len(values)

class TestAverage(unittest.TestCase):
    def test_normal(self):
        self.assertEqual(average([2, 4, 6]), 4)

    def test_empty(self):
        with self.assertRaises(ValueError):
            average([])

suite = unittest.defaultTestLoader.loadTestsFromTestCase(TestAverage)
result = unittest.TestResult()
suite.run(result)
print(result.testsRun, len(result.failures), len(result.errors))
2 0 0

Entry point, environments and packaging

Put the start of your program in a main() function and call it only when the file is run directly, with if __name__ == "__main__":. That way other files can import your code without starting the program. Use a virtual environment (python -m venv .venv) so each project has its own packages, and list the packages in requirements.txt or pyproject.toml. When the app is ready, a README with install and usage steps, and a version number, helps other people use it.

Example 6: main guard
def greet(name):
    return f"Hello, {name}!"

def main():
    print(greet("Asha"))

if __name__ == "__main__":
    main()
Hello, Asha!
Build in small steps. Get a tiny version working end to end, commit it, then add one feature at a time and test it. A working small program is worth more than a large unfinished one.

Python syntax

Syntax
from dataclasses import dataclass, field, asdict
@dataclass
class Item:
    name: str
    tags: list = field(default_factory=list)
Syntax
parser = argparse.ArgumentParser(prog="app")
parser.add_argument("--name")
args = parser.parse_args()
Syntax
logging.basicConfig(level=logging.INFO)
log = logging.getLogger(__name__)
log.info("message")
Syntax
def main():
    ...

if __name__ == "__main__":
    main()

Real-world applications

  • Command-line tools such as file organisers, note takers and report makers.
  • Small web services and APIs built on top of well-structured logic.
  • Desktop utilities that read and write local data files.
  • Automation of daily work such as renaming files or sending reports.
  • Back-end code shared by several interfaces, for example a CLI and a web page.

Common mistakes

Mistake: Putting all code in one giant file with input, logic and printing mixed together.
Fix: Separate logic into functions or modules that take values and return values, so they can be tested.
Mistake: Using a mutable default such as tags: list = [] in a dataclass.
Fix: Use field(default_factory=list); Python also rejects the direct mutable default.
Mistake: Catching every error with a bare except: and hiding the real problem.
Fix: Catch specific exceptions and log or re-raise the details.
Mistake: Hard-coding file paths such as C:\data\file.txt.
Fix: Use pathlib.Path and put paths and settings in one configuration place.
Mistake: Running code at import time with no main guard.
Fix: Use if __name__ == "__main__": so imports have no side effects.
Mistake: Installing every package into the system Python.
Fix: Create a virtual environment for each project and list dependencies in a requirements file.

Important tips

  • Write the function signature and a test first when the logic is tricky.
  • Keep functions short and give them one job.
  • Use type hints; they help readers and editors.
  • Log at INFO for normal events and ERROR for failures.
  • Add a README that shows how to install and run the app.

Key points summary

  • Separate interface, logic and storage.
  • Dataclasses reduce boilerplate for data holders.
  • JSON plus pathlib is a simple way to store data.
  • argparse builds command-line interfaces with help and validation.
  • logging is better than print for diagnostics.
  • Tests protect your code when you change it.
  • Use a main guard and a virtual environment.

Exam and interview points

  • Explain why the main guard is used.
  • Show a dataclass with a default_factory field.
  • Name the logging levels in order.
  • Explain what a virtual environment isolates.
  • Write a simple unittest with assertEqual and assertRaises.

Quick revision

  • Split code: interface, logic, storage
  • @dataclass writes __init__ and __repr__
  • json.dumps / json.loads plus Path.read_text
  • argparse for command-line options
  • logging levels: DEBUG < INFO < WARNING < ERROR < CRITICAL
  • unittest or pytest for tests
  • if __name__ == "__main__": main()
  • python -m venv .venv

Frequently asked questions

What is the difference between a script and an application?

A script does one job once. An application has several parts, handles errors and input, is tested and is meant to be used and changed over time.

Should I use unittest or pytest?

unittest comes with Python. pytest needs installing but has shorter tests and good reports. Both are fine, and pytest can run unittest tests.

Why use logging instead of print?

Logging has levels, can write to files, can be turned up or down without editing code and can include times and module names.

What does if __name__ == "__main__" do?

The code under it runs only when the file is started directly, not when another file imports it.

Do I need a framework to build an app?

No. Many tools are plain Python with the standard library. Frameworks help when you need a web interface, a database layer or a GUI.

Practise this chapter

25 practice questions Take the chapter quiz

Related chapters