Menu
CoddyTech

Allocation and Object Lifetime

Lesson 32 of 48 in Coddy's Python for C Developers course.

A C allocation returns storage that must be initialized and eventually freed according to its ownership contract. Python class calls create objects whose lifetimes are managed by the runtime. A normal instance of this simple class accepts attributes through assignment. a and b refer to one instance, so changing its weight through b is visible through a. No explicit pointer dereference operator is needed. Returning a Python object from a function is safe while a caller keeps a reference; returning a pointer to a dead C local object is not.

C: complete example.c

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
struct Parcel { int weight; };
int main(void) {
    struct Parcel *a = malloc(sizeof *a);
    if (a == NULL) return 1;
    a->weight = 2; struct Parcel *b = a; b->weight = 5;
    printf("%d\n", a->weight);
    free(a);
    return 0;
}

Python: complete example.py

class Parcel:
    pass
a = Parcel()
a.weight = 2
b = a
b.weight = 5
print(a.weight)

Watch the difference

Python del a removes that name, not necessarily the object: b may still keep it reachable. Do not rely on an exact destruction time for external resources; use context managers for files and similar resources. Python references are not general-purpose raw addresses.

Your code goes in parcel.py, functions.py. The locked driver.py is the entry file, supplies execution and checks, and cannot be edited.

challenge icon

Challenge

Beginner

In parcel.py define an empty Parcel class with pass. In functions.py implement make_parcel(label, weight), creating a fresh Parcel, setting label and weight, and returning it. The driver reads two label/weight pairs and an increase (all weights and increases nonnegative; labels may be empty), increases only the first parcel, prints both label:weight lines, then prints their identity comparison.

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.

A C struct fixes its member layout; ordinary instances of this Python class receive attributes through assignment.

Your code goes in parcel.py, functions.py. The locked driver.py is the entry file, supplies execution and checks, and cannot be edited.

Try it yourself

from parcel import Parcel
from functions import make_parcel

a = make_parcel(input(), int(input()))
b = make_parcel(input(), int(input()))
assert isinstance(a, Parcel) and isinstance(b, Parcel)
a.weight += int(input())
print(f"{a.label}:{a.weight}")
print(f"{b.label}:{b.weight}")
print(a is b)
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Python for C Developers

Practice on your own: Online Python compiler