Skip to content
Fix Code Error

What is the use of “assert”?

March 13, 2021 by Code Error
Posted By: Anonymous

I have been reading some source code and in several places I have seen the usage of assert.

What does it mean exactly? What is its usage?

Solution

The assert statement exists in almost every programming language. It helps detect problems early in your program, where the cause is clear, rather than later when some other operation fails.

When you do…

assert condition

… you’re telling the program to test that condition, and immediately trigger an error if the condition is false.

In Python, it’s roughly equivalent to this:

if not condition:
    raise AssertionError()

Try it in the Python shell:

>>> assert True # nothing happens
>>> assert False
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AssertionError

Assertions can include an optional message, and you can disable them when running the interpreter.

To print a message if the assertion fails:

assert False, "Oh no! This assertion failed!"

Do not use parenthesis to call assert like a function. It is a statement. If you do assert(condition, message) you’ll be running the assert with a (condition, message) tuple as first parameter.

As for disabling them, when running python in optimized mode, where __debug__ is False, assert statements will be ignored. Just pass the -O flag:

python -O script.py

See here for the relevant documentation.

Answered By: Anonymous

Related Articles

  • What is the worst programming language you ever worked with?
  • Manually raising (throwing) an exception in Python
  • Reference — What does this symbol mean in PHP?
  • How do SO_REUSEADDR and SO_REUSEPORT differ?
  • Can't install via pip because of egg_info error
  • How do the PHP equality (== double equals) and…
  • What's the difference between eval, exec, and compile?
  • Onclick event not happening when slick slider is…
  • Getting started with Haskell
  • Best practice multi language website
  • Calculate the mean by group
  • error LNK2005: ✘✘✘ already defined in…
  • What does "Fatal error: Unexpectedly found nil while…
  • How to turn off ALL conventions in Entity Framework Core 5
  • data.table vs dplyr: can one do something well the…
  • npm install error in vue
  • Next.js making a timeout stop with a react state
  • Oracle: If Table Exists
  • How do I include certain conditions in SQL Count
  • PHP parse/syntax errors; and how to solve them
  • What does the "assert" keyword do?
  • Why does C++ code for testing the Collatz conjecture…
  • How can I wrap all BeautifulSoup existing…
  • How can I fix MySQL error #1064?
  • Elegant ways to support equivalence ("equality") in…
  • What is your most productive shortcut with Vim?
  • What is Common Gateway Interface (CGI)?
  • Logging best practices
  • java.sql.SQLException: - ORA-01000: maximum open…
  • What is an AssertionError? In which case should I…
  • How does PHP 'foreach' actually work?
  • What is the difference between bottom-up and top-down?
  • Why call git branch --unset-upstream to fixup?
  • Memcached vs. Redis?
  • What are the undocumented features and limitations…
  • What does a "Cannot find symbol" or "Cannot resolve…
  • How to handle AssertionError in Python and find out…
  • For-each over an array in JavaScript
  • What is a NullReferenceException, and how do I fix it?
  • What's the best way of scraping data from a website?
  • row-level trigger vs statement-level trigger
  • discord.ext.commands.errors.CommandInvokeError:…
  • Is there a built-in function to print all the…
  • Why isn't Python very good for functional programming?
  • Specifying java version in maven - differences…
  • What does this symbol mean in JavaScript?
  • Smart way to truncate long strings
  • javascript .replace and .trim not working in vuejs
  • jQuery Mobile: document ready vs. page events
  • Dafny prove lemmas in a high-order polymorphic function
  • Jetty: HTTP ERROR: 503/ Service Unavailable
  • What is the origin of foo and bar?
  • #define macro for debug printing in C?
  • How to update Python?
  • How do I merge two dictionaries in a single…
  • How to internationalize a React Native Expo App?
  • Ukkonen's suffix tree algorithm in plain English
  • The null object does not have a method []=
  • Why doesn't the height of a container element…
  • How to detect if multiple keys are pressed at once…
  • What does the CSS rule "clear: both" do?
  • Usage of __slots__?
  • How to insert data in only one type of Vector in…
  • What is the difference between a strongly typed…
  • React google map is not updating
  • Database development mistakes made by application developers
  • What exactly is std::atomic?
  • Check synchronously if file/directory exists in Node.js
  • What does "Could not find or load main class" mean?
  • open telemetry InMemorySpanExporter not reseting…
  • What is an optional value in Swift?
  • What does "dereferencing" a pointer mean?
  • Dragstart not getting invoked after reordering the elements
  • Creating a singleton in Python
  • Start redis-server with config file
  • What does Ruby have that Python doesn't, and vice versa?
  • Difference between variable declaration syntaxes in…
  • What are type hints in Python 3.5?
  • Why is “while ( !feof (file) )” always wrong?
  • How can I test my Dao method with Mockito If I get…
  • Reference - What does this regex mean?
  • SQL query return data from multiple tables
  • How to truncate float values?
  • How to catch and print the full exception traceback…
  • Eclipse will not start and I haven't changed anything
  • How to generate a random string of a fixed length in Go?
  • Why do I have to "git push --set-upstream origin "?
  • How do you parse and process HTML/XML in PHP?
  • What is the difference between dynamic programming…
  • What is difference between functional and imperative…
  • Is there any way to kill a Thread?
  • Delay content of test of Cloud Functions with Mocha
  • What is the copy-and-swap idiom?
  • Relative imports for the billionth time
  • Virtual Memory Usage from Java under Linux, too much…
  • Copy a file in a sane, safe and efficient way
  • AddTransient, AddScoped and AddSingleton Services…
  • Plotting curve over several subplots in R
  • Do you (really) write exception safe code?
  • Clang vs GCC - which produces faster binaries?

Disclaimer: This content is shared under creative common license cc-by-sa 3.0. It is generated from StackExchange Website Network.

Post navigation

Previous Post:

How to split a String by space

Next Post:

How to select the nth row in a SQL database table?

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

.net ajax android angular arrays aurelia backbone.js bash c++ css dataframe ember-data ember.js excel git html ios java javascript jquery json laravel linux list mysql next.js node.js pandas php polymer polymer-1.0 python python-3.x r reactjs regex sql sql-server string svelte typescript vue-component vue.js vuejs2 vuetify.js

  • you shouldn’t need to use z-index
  • No column in target database, but getting “The schema update is terminating because data loss might occur”
  • Angular – expected call-signature: ‘changePassword’ to have a typedeftslint(typedef)
  • trying to implement NativeAdFactory imports deprecated method by default in flutter java project
  • What should I use to get an attribute out of my foreign table in Laravel?
© 2022 Fix Code Error