Propagate Errors across Native Boundaries
Core idea
Most C API functions signal failure through a documented sentinel and set the current thread’s Python exception indicator. A pointer-returning extension commonly returns NULL with an exception set; an integer-returning API may have a different sentinel. For PyLong_AsLong, -1 can be valid, so check PyErr_Occurred when it returns -1. Release owned resources before propagating errors.
for x in ('-1','bad'): try: print(int(x)) except ValueError: print('invalid')The Python-level analogue separates successful negative data from failure.
Expected output:
-1invalidClean up before propagating
events=[]def work(): try: raise ValueError('invalid') finally: events.append('released')try: work()except ValueError: print(events)This Python-level example models the need for cleanup on failure; native code must manage ownership explicitly.
Expected output:
['released']Common mistake
Never return a normal object while leaving an exception pending, or NULL without an appropriate exception. Do not swallow an error unless deliberately translating or handling it.
Practice
Review native fixture as_long with -1, a nonnumeric string and an overflowing integer; identify the distinct success and failure paths.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Native errors
Check your understanding of native errors.
What is printed?
print(int("-1"))What is printed?
try: int("x")except ValueError: print("error")When PyLong_AsLong returns -1 what else matters?
What should an extension do on failure?