Properties and Validated State
Lesson 36 of 48 in Coddy's Python for C Developers course.
C can enforce validation through setter functions, especially when an opaque struct hides fields from callers. Python @property lets attribute reads call a getter and attribute assignment call a setter. Validate before assigning the backing _level so a rejected change preserves the old value. Initialize through the property to apply the same rule at construction. A leading underscore marks an internal attribute by convention, not memory protection. __str__ supplies readable text when str or print formats an instance.
C: complete example.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
struct Meter { int level; };
int set_level(struct Meter *m, int value) { if (value < 0) return 0; m->level = value; return 1; }
int main(void) {
struct Meter m = {2};
int ok = set_level(&m, -1);
printf("%d %d\n", ok, m.level);
return 0;
}Python: complete example.py
class Meter:
def __init__(self, level):
self.level = level
@property
def level(self):
return self._level
@level.setter
def level(self, value):
if value < 0:
raise ValueError("negative")
self._level = value
m = Meter(2)
try:
m.level = -1
except ValueError:
print(m.level)Watch the difference
Directly assigning self.level inside its own setter would recurse. Store the validated value under a different backing name. A property is executable behavior, unlike an ordinary C struct field access.
Your code goes in meter.py. The locked driver.py is the entry file, supplies execution and checks, and cannot be edited.
Challenge
BeginnerImplement Meter(level) with a level property backed by _level. Construction and later assignment accept nonnegative integers; negative values raise ValueError without changing state. Initialize through the property. __str__ returns level=N. The driver reads initial level and proposed integer levels, prints ok or invalid then the meter after each attempt, or prints the initial meter once if there are no attempts. Rejected construction prints only invalid start.
Implement the named definitions in the editable modules without input or printing. The driver owns input/output and may call the APIs again on fresh data without producing extra output.
Attribute assignment can execute a Python setter; it is not a plain C struct member write.
Your code goes in meter.py. The locked driver.py is the entry file, supplies execution and checks, and cannot be edited.
Try it yourself
from meter import Meter
initial = int(input())
values = [int(x) for x in input().split()]
try:
meter = Meter(initial)
except ValueError:
print("invalid start")
else:
for value in values:
try:
meter.level = value
print("ok")
except ValueError:
print("invalid")
print(meter)
if not values:
print(meter)
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Python for C Developers
1From C Programs to Python
Run Python Without mainPrinting Without Format CodesNames Versus Typed StorageDivision and Integer LimitsSuites Instead of BracesRecap: A Python Receipt4Iteration and Transformations
Iteration Without PointersIndexes Without Pointer MathSentinels and Loop ControlComprehensions and SortingRecap: Stable Ranking7Structs to Python Objects
Allocation and Object LifetimeInitializing Object StateBound Methods Versus CallbacksShared State and ShadowingProperties and Validated StateRecap: Account State2Values and Truth Tests
Absence Is Not a Null PointerContent Versus Object IdentityTruth Tests and OperandsConditional Value SelectionRecap: Missing or Eligible3Containers and Aliasing
Lists Versus C ArraysTuples and Struct ValuesMappings and Lookup LoopsPointers, Copies, and AliasesRecap: Inventory Collections6Contracts, Errors, and Modules
Text Input and Exact OutputError Codes Versus ExceptionsImports Are Not IncludesAnnotations Versus C TypesRecap: Validate a Batch9Project: An Order Processor
Project: Model an OrderProject: Pricing PoliciesPractice on your own: Online Python compiler