A is for assert - Python A to Z Dark _ □ ✕
  • Posts
  • About
  • Debug
Post

A is for assert - Python A to Z

Published
2026-08-02 00:00 UTC (precision: second)
Source feed
Juha-Matti Santala - Community Builder. Dreamer. Adventurer. excluded
Link
https://hamatti.org/posts/a-is-for-assert-python-a-to-z/
Canonical
https://hamatti.org/posts/a-is-for-assert-python-a-to-z
Length
3897 runes
Extracted text
Python A-Z is a blog series about Python. Each day, I share insights, ideas and examples for different parts of Python development that match with the letter of the day. Blaugust is an annual blogging festival in August where the goal is to write a blog post every day of the month. The assert statement is a built-in Python statement that gives developers a nice short hand for raising an AssertionError based on a condition. assert expression, "message" An assert statement is syntactic shorthand for if __debug__: if not expression: raise AssertionError("message") To see how it works in practice, let’s jump into a REPL session: >>> age = 21 >>> assert age > 18, f"Needs to be over 18 years old, {age=}" >>> age = 16 >>> assert age > 18, f"Needs to be over 18 years old, {age=}" Traceback (most recent call last): File "<python-input-5>", line 1, in <module> assert age > 18, f"Needs to be over 18 years old, {age=}" ^^^^^^^^ AssertionError: Needs to be over 18 years old, age=16 When the expression is truthy, nothing happens. When it’s falsy however, Python will raise an AssertionError and if a message was provided, it will be printed after the error in the traceback. Writing good assertion messages will make your life easier in the future. When you write your code, you have a good idea of what the assertion tests but as time goes on, the memories will fade and if you run into a random AssertionError in your script (see use case 1 below), it may require a lot of mental work to get back on track. Use case 1: failsafe for scripting It’s handy for debugging but also as a sort of failsafe for scripts that you run manually. When I write shell script style scripts with Python, I don’t always need to write the most robust code but a quick “make sure this is so” check that stops the execution is enough. In a use case like that, adding asserts is a quick way to make sure unexpected issues in data don’t make their way to wreck havoc later in the script. When the script is run manually, it’s perfectly fine for it to crash to an unhandled exception. That’s not usually the case if you’re running it automatically (for example in CI or as a cronjob) so in those cases you want to make sure your script can either recover or properly logs its errors. Let’s look at a simplified example: #!/usr/bin/env -S uv run --quiet --script import sys path = sys.argv[1] assert '..' not in path, f"Can't go up in directory hierarchy, {path=}" # Run the script (the shebang of the previous script makes it handy to write single-file executable Python scripts using uv) Here, we have a script that accepts a file path as a command line argument and does something with it. I wanted to make sure it doesn’t accidentally escape to do things in folders above where it’s ran. This could happen accidentally for example if it’s being run by another script that could have inserted an .. into its list of filenames. It’s not a perfect, robust error boundary as there could be files with double periods but it’s good enough for my script’s use case. The provided message lets me know if it skipped something because of double period. NOTE: It’s important to note that assertions will be disabled if the code is run with optimisations enabled (either by running the script with python -O or python -OO or having the environment variable PYTHONOPTIMIZE set to a non-zero value). This means you cannot and should not rely on asserts for data validation generally. Use case 2: pytest Popular testing library pytest uses asserts for test cases. def test_empty_list_sums_to_zero(): assert sum([]) == 0 I find it much more elegant and readable than the custom assertion libraries like unittest’s self.assertEqual. It also allows writing tests without having to import anything in the test suite. When you run this through pytest, it will check whether sum([]) returns 0 or not and either passes or fails the test.
Stored topics

Every stored assignment is listed, including rows below the current cutoff (0.75), so a missing tag can be explained.

Concept Code Score Meter Margin Origin Path
science and technology science-and-technology 0.98 3.85 direct science and technology
economy, business and finance economy-business-and-finance 0.95 3.03 ↑derived from local:software-development economy, business and finance
products and services products-and-services 0.95 3.03 ↑derived from local:software-development economy, business and finance > products and services
computing and information technology computing-and-information-technology 0.95 3.03 ↑derived from local:software-development economy, business and finance > products and services > computing and information technology
software and applications software-and-applications 0.95 3.03 ↑derived from local:software-development economy, business and finance > products and services > computing and information technology > software and applications
Software development software-development 0.95 3.03 direct economy, business and finance > products and services > computing and information technology > software and applications > Software development
Open source open-source 0.12 -2.01 direct economy, business and finance > products and services > computing and information technology > software and applications > Open source
technology and engineering technology-and-engineering 0.04 -3.19 ↑derived from 20001298 science and technology > technology and engineering
information technology and computer science information-technology-and-computer 0.04 -3.19 ↑derived from 20001298 science and technology > technology and engineering > information technology and computer science
artificial intelligence artificial-intelligence 0.04 -3.19 direct science and technology > technology and engineering > information technology and computer science > artificial intelligence
arts, culture, entertainment and media arts-culture-entertainment-and-media 0.02 -4.15 ↑derived from local:blogging arts, culture, entertainment and media
mass media mass-media 0.02 -4.15 ↑derived from local:blogging arts, culture, entertainment and media > mass media
social media social-media 0.02 -4.15 ↑derived from local:blogging arts, culture, entertainment and media > mass media > social media
Blogging blogging 0.02 -4.15 direct arts, culture, entertainment and media > mass media > social media > Blogging
Information security information-security 0.01 -4.41 direct science and technology > technology and engineering > information technology and computer science > Information security
scientific research scientific-research 0.01 -4.45 ↑derived from 20000739 science and technology > scientific research
scientific exploration scientific-exploration 0.01 -4.45 ↑derived from 20000739 science and technology > scientific research > scientific exploration
space exploration space-exploration 0.01 -4.45 direct science and technology > scientific research > scientific exploration > space exploration
education education 0.01 -4.57 direct education
lifestyle and leisure lifestyle-and-leisure 0.01 -4.61 ↑derived from local:mmorpg lifestyle and leisure
leisure leisure 0.01 -4.61 ↑derived from local:mmorpg lifestyle and leisure > leisure
game game 0.01 -4.61 ↑derived from local:mmorpg lifestyle and leisure > leisure > game
video game video-game 0.01 -4.61 ↑derived from local:mmorpg lifestyle and leisure > leisure > game > video game
MMORPG mmorpg 0.01 -4.61 direct lifestyle and leisure > leisure > game > video game > MMORPG
society society 0.01 -4.71 direct society
arts and entertainment arts-and-entertainment 0.01 -4.81 ↑derived from 20000013 arts, culture, entertainment and media > arts and entertainment
literature literature 0.01 -4.81 direct arts, culture, entertainment and media > arts and entertainment > literature
media and entertainment industry media-and-entertainment-industry 0.00 -5.31 ↑derived from 20000306 economy, business and finance > products and services > media and entertainment industry
books and publishing books-and-publishing 0.00 -5.31 direct economy, business and finance > products and services > media and entertainment industry > books and publishing
Cryptography cryptography 0.00 -5.37 direct science and technology > technology and engineering > information technology and computer science > Cryptography
human interest human-interest 0.00 -5.37 ↑derived from 20000498 human interest
award and prize award-and-prize 0.00 -5.37 direct human interest > award and prize
culture culture 0.00 -5.40 direct arts, culture, entertainment and media > culture
labour labour 0.00 -5.44 direct labour
family family 0.00 -5.44 direct society > family
Tabletop gaming tabletop-gaming 0.00 -5.49 direct lifestyle and leisure > leisure > game > Tabletop gaming
politics and government politics-and-government 0.00 -5.57 direct politics and government
crime, law and justice crime-law-and-justice 0.00 -5.68 ↑derived from 20000086 crime, law and justice
crime crime 0.00 -5.68 ↑derived from 20000086 crime, law and justice > crime
cyber crime cyber-crime 0.00 -5.68 direct crime, law and justice > crime > cyber crime
film industry film-industry 0.00 -5.76 direct economy, business and finance > products and services > media and entertainment industry > film industry
television television 0.00 -5.85 direct arts, culture, entertainment and media > mass media > television
environment environment 0.00 -5.89 direct environment
weather weather 0.00 -5.91 ↑derived from 20001128 weather
weather forecast weather-forecast 0.00 -5.91 direct weather > weather forecast
natural science natural-science 0.00 -5.99 ↑derived from 20000719 science and technology > natural science
biology biology 0.00 -5.99 direct science and technology > natural science > biology
social sciences social-sciences 0.00 -6.03 ↑derived from 20000747 science and technology > social sciences
history history 0.00 -6.03 direct science and technology > social sciences > history
religion religion 0.00 -6.04 direct religion
health health 0.00 -6.24 direct health
Self-hosting self-hosting 0.00 -6.25 direct economy, business and finance > products and services > computing and information technology > Self-hosting
sport sport 0.00 -6.33 ↑derived from 20001183 sport
competition discipline competition-discipline 0.00 -6.33 ↑derived from 20001183 sport > competition discipline
eSports esports 0.00 -6.33 direct sport > competition discipline > eSports
fundamental rights fundamental-rights 0.00 -6.39 ↑derived from 20001300 society > fundamental rights
privacy privacy 0.00 -6.39 direct society > fundamental rights > privacy
board game board-game 0.00 -6.48 direct lifestyle and leisure > leisure > game > board game
streaming service streaming-service 0.00 -6.54 direct economy, business and finance > products and services > media and entertainment industry > streaming service
conflict, war and peace conflict-war-and-peace 0.00 -6.64 direct conflict, war and peace
health treatment and procedure health-treatment-and-procedure 0.00 -6.64 ↑derived from 20000465 health > health treatment and procedure
diet diet 0.00 -6.64 direct health > health treatment and procedure > diet
hobby hobby 0.00 -6.81 ↑derived from 20000568 lifestyle and leisure > leisure > hobby
food and drink enthusiasm food-and-drink-enthusiasm 0.00 -6.81 direct lifestyle and leisure > leisure > hobby > food and drink enthusiasm
music music 0.00 -7.09 direct arts, culture, entertainment and media > arts and entertainment > music
exercise and fitness exercise-and-fitness 0.00 -7.15 direct lifestyle and leisure > wellness > exercise and fitness
wellness wellness 0.00 -7.15 ↑derived from 20001239 lifestyle and leisure > wellness
card game card-game 0.00 -7.16 direct lifestyle and leisure > leisure > game > card game
visual arts visual-arts 0.00 -7.19 ↑derived from 20000036 arts, culture, entertainment and media > arts and entertainment > visual arts
photography photography 0.00 -7.19 direct arts, culture, entertainment and media > arts and entertainment > visual arts > photography
podcast podcast 0.00 -7.29 direct economy, business and finance > products and services > media and entertainment industry > podcast
consumer goods consumer-goods 0.00 -7.29 ↑derived from 20001160 economy, business and finance > products and services > consumer goods
handicrafts handicrafts 0.00 -7.29 direct economy, business and finance > products and services > consumer goods > handicrafts
disaster, accident and emergency incident disaster-accident-and-emergency-incident 0.00 -7.31 direct disaster, accident and emergency incident
lifestyle lifestyle 0.00 -7.39 ↑derived from 20001257 lifestyle and leisure > lifestyle
house and home house-and-home 0.00 -7.39 ↑derived from 20001257 lifestyle and leisure > lifestyle > house and home
gardening gardening 0.00 -7.39 direct lifestyle and leisure > lifestyle > house and home > gardening
public health public-health 0.00 -7.46 direct health > public health
animation animation 0.00 -7.51 direct arts, culture, entertainment and media > arts and entertainment > animation
disease and condition disease-and-condition 0.00 -7.62 ↑derived from 20000458 health > disease and condition
mental health and disorder mental-health-and-disorder 0.00 -7.62 direct health > disease and condition > mental health and disorder
climate change climate-change 0.00 -7.68 direct environment > climate change
travel and tourism travel-and-tourism 0.00 -8.35 direct lifestyle and leisure > leisure > travel and tourism

← Back to posts

feedtagger 0.1.0-dev model: modernbert-base-zeroshot-v2.0/int8@all-s256 651 posts 0 unclassified min score 0.75