Register to get access to free programming courses with interactive exercises

Invariants Python: Building data abstractions

Abstraction allows us not to think about the details of the implementation and to focus on its use. Moreover, the implementation of an abstraction can be rewritten, if necessary, without fear of breaking the code that uses it. But there is another reason why you need to use abstraction-maintaining invariants.

In programming, an invariant is a logical expression that defines the consistency of a state or data set.

Let's look at an example. When we described the constructor and selectors for rational numbers, we implicitly implied the following invariants:

num = make_rational(numer, denom)
numer == get_numer(num)
# True
denom == get_denom(num)
# True

By passing the numerator and denominator of the rational number constructor, we expect to get the same numbers when we apply the selectors to the rational ones. It is how we ensure that the abstraction works — we test the code in practice.

Invariants exist for every operation. And they can be tricky. For example, we can compare rational numbers to each other, but not directly, because we can represent the same fractions in different ways: 1/2 and 2/4.

Code that doesn't take this into account won't work:

num1 = make_rational(2, 4)
num2 = make_rational(8, 16)
num1 == num2

Sign up

Programming courses for beginners and experienced developers. Start training for free

  • 130 courses, 2000+ hours of theory
  • 1000 practical tasks in a browser
  • 360 000 students
By sending this form, you agree to our Personal Policy and Service Conditions

Our graduates work in companies:

<span class="translation_missing" title="translation missing:">Bookmate</span>
<span class="translation_missing" title="translation missing:">Healthsamurai</span>
<span class="translation_missing" title="translation missing:">Dualboot</span>
<span class="translation_missing" title="translation missing:">Abbyy</span>
Suggested learning programs
Developing web applications with Django
10 months
from scratch
under development
Start at any time

Use Hexlet to the fullest extent!

  • Ask questions about the lesson
  • Test your knowledge in quizzes
  • Practice in your browser
  • Track your progress

Sign up or sign in

By sending this form, you agree to our Personal Policy and Service Conditions
Toto Image

Ask questions if you want to discuss a theory or an exercise. Hexlet Support Team and experienced community members can help find answers and solve a problem.