Skip to content

Commit 420b088

Browse files
Fix: Correct exceptions doc; trim generic object() examples
exceptions.md: - Nest NotImplementedError and RecursionError under RuntimeError, and TabError under IndentationError, matching CPython's MRO - Remove duplicate BrokenPipeError; note EnvironmentError/IOError are aliases of OSError, not subclasses - Add BaseExceptionGroup to the tree and mark exception groups 3.11+ - Replace examples that raised the wrong exception: OverflowError (math.exp/float of huge int), MemoryError ([0] * 2**62), BufferError (bytearray resize with exported memoryview), FloatingPointError (NumPy seterr), UnicodeTranslateError (codec error handler note) - Add missing imports, guard finally-block cleanup against unbound variable, use socket instances instead of module-level calls object_func.md: - Remove generic example sections (sentinel, class creation, MRO, attribute access) not specific to complexity documentation Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
1 parent fe44149 commit 420b088

2 files changed

Lines changed: 47 additions & 155 deletions

File tree

docs/builtins/exceptions.md

Lines changed: 47 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ BaseException (O(1) to raise and catch)
1111
├── SystemExit - Program exit (exit code)
1212
├── KeyboardInterrupt - User interrupt (Ctrl+C)
1313
├── GeneratorExit - Generator cleanup
14+
├── BaseExceptionGroup - Multiple exceptions (Python 3.11+)
1415
└── Exception (base for most exceptions)
1516
├── ArithmeticError
1617
│ ├── FloatingPointError - Float operation error
@@ -20,7 +21,7 @@ BaseException (O(1) to raise and catch)
2021
├── AttributeError - Attribute not found
2122
├── BufferError - Buffer operation failed
2223
├── EOFError - End of file reached
23-
├── ExceptionGroup - Multiple exceptions
24+
├── ExceptionGroup - Multiple exceptions (also a BaseExceptionGroup; 3.11+)
2425
├── ImportError
2526
│ └── ModuleNotFoundError - Module not found
2627
├── LookupError
@@ -40,30 +41,28 @@ BaseException (O(1) to raise and catch)
4041
│ ├── InterruptedError - Interrupted
4142
│ ├── BlockingIOError - Blocking operation
4243
│ ├── ChildProcessError - Child process error
43-
│ ├── BrokenPipeError - Broken pipe
4444
│ ├── ConnectionError - Connection error
4545
│ │ ├── BrokenPipeError
4646
│ │ ├── ConnectionAbortedError
4747
│ │ ├── ConnectionRefusedError
4848
│ │ └── ConnectionResetError
49-
│ ├── EnvironmentError - Environment error
50-
│ └── IOError - I/O error
49+
│ └── (EnvironmentError and IOError are aliases of OSError)
5150
├── ReferenceError - Weak reference deleted
5251
├── RuntimeError - Generic runtime error
53-
├── RecursionError - Max recursion exceeded
52+
│ ├── NotImplementedError - Not implemented
53+
│ └── RecursionError - Max recursion exceeded
5454
├── StopIteration - Iterator exhausted
5555
├── StopAsyncIteration - Async iterator exhausted
5656
├── SyntaxError
57-
── IndentationError - Indentation error
58-
│ └── TabError - Tab/space mixing
57+
── IndentationError - Indentation error
58+
└── TabError - Tab/space mixing
5959
├── SystemError - Internal interpreter error
6060
├── TypeError - Wrong type
6161
├── ValueError - Wrong value
6262
│ └── UnicodeError
6363
│ ├── UnicodeDecodeError - Decode failed
6464
│ ├── UnicodeEncodeError - Encode failed
6565
│ └── UnicodeTranslateError - Translate failed
66-
├── NotImplementedError - Not implemented
6766
└── Warning (warnings don't stop execution)
6867
├── DeprecationWarning - Feature deprecated
6968
├── PendingDeprecationWarning - Future deprecation
@@ -115,6 +114,8 @@ except SystemExit as e:
115114
Raised by Ctrl+C. Not caught by `except Exception`.
116115

117116
```python
117+
import sys
118+
118119
try:
119120
while True:
120121
process()
@@ -151,25 +152,35 @@ except ZeroDivisionError:
151152
```
152153

153154
#### `FloatingPointError` - Float Operation Error
155+
CPython itself no longer raises this — invalid float operations return `inf`/`nan` instead. Mainly seen with NumPy configured to raise:
156+
154157
```python
155-
import warnings
156-
warnings.simplefilter("error", FloatingPointError)
158+
import numpy as np
159+
160+
np.seterr(all='raise')
157161

158162
try:
159-
result = float('inf') - float('inf') # NaN
163+
result = np.float64(1.0) / np.float64(0.0)
160164
except FloatingPointError:
161165
print("Invalid float operation")
162166
```
163167

164168
#### `OverflowError` - Number Too Large
169+
Python ints never overflow (arbitrary precision); this is raised when a *float* result is too large.
170+
165171
```python
166-
import sys
172+
import math
167173

168174
try:
169-
large = sys.maxsize + 1
170-
power = 10 ** 1000000 # May overflow in some contexts
175+
result = math.exp(1000) # Result too large for a float
171176
except OverflowError:
172177
print("Number too large")
178+
179+
# Also raised when converting a huge int to float
180+
try:
181+
f = float(10 ** 1000)
182+
except OverflowError:
183+
print("Int too large for float")
173184
```
174185

175186
#### `ArithmeticError` - Base Arithmetic Error
@@ -302,12 +313,12 @@ except UnicodeEncodeError as e:
302313

303314
#### `UnicodeTranslateError` - Translation Failed
304315
```python
305-
# Raised during str.translate() with invalid mapping
316+
# Rarely raised by Python itself; mainly seen in custom
317+
# codec error handlers
306318
try:
307-
text = "hello"
308-
result = text.translate({0: "x"}) # Bad mapping
309-
except UnicodeTranslateError:
310-
print("Translation failed")
319+
raise UnicodeTranslateError("hello", 0, 1, "example reason")
320+
except UnicodeTranslateError as e:
321+
print(f"Translation failed: {e.reason}")
311322
```
312323

313324
### I/O and OS Errors - Time: O(1)
@@ -411,7 +422,7 @@ except ChildProcessError:
411422
import socket
412423

413424
try:
414-
socket.send(data) # Pipe/socket closed
425+
sock.send(data) # Pipe/socket closed
415426
except BrokenPipeError:
416427
print("Pipe broken")
417428
```
@@ -421,38 +432,39 @@ Base class for connection errors.
421432

422433
```python
423434
try:
424-
socket.connect(("unreachable.host", 80))
435+
sock.connect(("unreachable.host", 80))
425436
except ConnectionError:
426437
print("Connection failed")
427438
```
428439

429440
#### `ConnectionRefusedError` - Connection Refused
430441
```python
431442
try:
432-
socket.connect(("localhost", 12345)) # No server listening
443+
sock.connect(("localhost", 12345)) # No server listening
433444
except ConnectionRefusedError:
434445
print("Server refused connection")
435446
```
436447

437448
#### `ConnectionAbortedError` - Connection Aborted
438449
```python
439450
try:
440-
socket.recv(1024) # Connection aborted
451+
sock.recv(1024) # Connection aborted
441452
except ConnectionAbortedError:
442453
print("Connection aborted")
443454
```
444455

445456
#### `ConnectionResetError` - Connection Reset
446457
```python
447458
try:
448-
socket.send(data) # Peer reset connection
459+
sock.send(data) # Peer reset connection
449460
except ConnectionResetError:
450461
print("Connection reset")
451462
```
452463

453464
#### `ProcessLookupError` - Process Not Found
454465
```python
455466
import os
467+
import signal
456468

457469
try:
458470
os.kill(999999, signal.SIGTERM) # PID doesn't exist
@@ -567,7 +579,7 @@ except ReferenceError:
567579
#### `MemoryError` - Out of Memory
568580
```python
569581
try:
570-
huge_list = [0] * (10 ** 100) # Impossible to allocate
582+
huge_list = [0] * (2 ** 62) # Impossible to allocate
571583
except MemoryError:
572584
print("Out of memory")
573585
```
@@ -613,8 +625,11 @@ except SystemError:
613625

614626
#### `BufferError` - Buffer Operation Failed
615627
```python
628+
ba = bytearray(b"data")
629+
view = memoryview(ba)
630+
616631
try:
617-
memoryview(5) # Can't create memoryview of int
632+
ba.extend(b"more") # Can't resize while a view is exported
618633
except BufferError:
619634
print("Invalid buffer operation")
620635
```
@@ -677,6 +692,8 @@ except NotImplementedError:
677692

678693
### Exception Groups - Time: O(n) where n = exceptions
679694

695+
Available in Python 3.11+.
696+
680697
#### `ExceptionGroup` - Multiple Exceptions
681698
```python
682699
try:
@@ -815,6 +832,7 @@ except AppError:
815832
### Finally Block - Time: O(1)
816833

817834
```python
835+
resource = None
818836
try:
819837
resource = acquire_resource()
820838
use_resource(resource)
@@ -823,8 +841,9 @@ except Exception as e:
823841
else:
824842
print("Success")
825843
finally:
826-
# Always executes
827-
cleanup_resource(resource)
844+
# Always executes; guard in case acquire_resource() raised
845+
if resource is not None:
846+
cleanup_resource(resource)
828847
```
829848

830849
### Context Managers - Time: O(1)

docs/builtins/object_func.md

Lines changed: 0 additions & 127 deletions
Original file line numberDiff line numberDiff line change
@@ -147,133 +147,6 @@ obj == obj # True - O(1)
147147
obj == obj2 # False - O(1) for base object
148148
```
149149

150-
## Practical Examples
151-
152-
### Sentinel Value
153-
154-
```python
155-
# O(1) - use object as unique sentinel
156-
_MISSING = object() # Unique marker
157-
158-
def get_value(d, key):
159-
result = d.get(key, _MISSING)
160-
if result is _MISSING:
161-
# Handle missing case
162-
return None
163-
return result
164-
165-
data = {'a': 1, 'b': 2}
166-
get_value(data, 'a') # 1
167-
get_value(data, 'c') # None
168-
```
169-
170-
### Default Instance
171-
172-
```python
173-
# O(1) - use object as default
174-
def process(config=None):
175-
if config is None:
176-
config = object() # Default
177-
178-
# Process with config
179-
return config
180-
181-
result = process() # Uses default object
182-
```
183-
184-
### Type Checking
185-
186-
```python
187-
# O(1) - check if something is an object (everything is)
188-
def is_object(x):
189-
return isinstance(x, object)
190-
191-
is_object(42) # True - all things
192-
is_object("string") # True
193-
is_object([1, 2]) # True
194-
is_object(object()) # True
195-
```
196-
197-
## Object Interface
198-
199-
```python
200-
# O(1) - common object methods/attributes
201-
obj = object()
202-
203-
# Type
204-
type(obj) # <class 'object'>
205-
206-
# Identity
207-
id(obj) # Memory address - O(1)
208-
209-
# Representation
210-
str(obj) # '<object object at 0x...>'
211-
repr(obj) # '<object object at 0x...>'
212-
213-
# Hashing
214-
hash(obj) # O(1) - based on id
215-
216-
# Class
217-
obj.__class__ # <class 'object'>
218-
219-
# Documentation
220-
obj.__doc__ # String
221-
```
222-
223-
## Class Creation
224-
225-
```python
226-
# O(1) - define custom classes
227-
class CustomClass(object):
228-
"""A custom class."""
229-
230-
def __init__(self, value):
231-
self.value = value # O(1)
232-
233-
def __str__(self):
234-
return f"Custom({self.value})"
235-
236-
# Create instance
237-
obj = CustomClass(42) # O(1) - __init__ is O(1)
238-
```
239-
240-
## Multiple Inheritance
241-
242-
```python
243-
# O(1) - object at end of MRO
244-
class A(object):
245-
pass
246-
247-
class B(object):
248-
pass
249-
250-
class C(A, B): # Multiple inheritance
251-
pass
252-
253-
C.__mro__ # (C, A, B, object)
254-
# object is always last
255-
```
256-
257-
## Attribute Access
258-
259-
```python
260-
# O(1) - default attribute behavior
261-
obj = object()
262-
263-
# Can't add attributes to base object
264-
try:
265-
obj.name = "test" # AttributeError
266-
except AttributeError:
267-
pass
268-
269-
# But custom classes can
270-
class Custom:
271-
pass
272-
273-
c = Custom()
274-
c.name = "test" # O(1) - works
275-
```
276-
277150
## Edge Cases
278151

279152
### Singleton Pattern

0 commit comments

Comments
 (0)