@@ -1344,6 +1344,7 @@ def __init__(self,
13441344 """
13451345
13461346 self ._closed = False
1347+ self ._initialized = False
13471348
13481349 self ._reader = None
13491350 self ._own_stream = None
@@ -1398,6 +1399,9 @@ def __init__(self,
13981399
13991400 # Store the file to close it later
14001401 self ._backing_file = file
1402+
1403+ # Mark as initialized after successful creation
1404+ self ._initialized = True
14011405
14021406 except Exception as e :
14031407 if self ._own_stream :
@@ -1458,6 +1462,9 @@ def __init__(self,
14581462 )
14591463
14601464 self ._backing_file = file
1465+
1466+ # Mark as initialized after successful creation
1467+ self ._initialized = True
14611468 except Exception as e :
14621469 if self ._own_stream :
14631470 self ._own_stream .close ()
@@ -1509,12 +1516,11 @@ def __init__(self,
15091516 )
15101517 )
15111518
1519+ # Mark as initialized after successful creation
1520+ self ._initialized = True
1521+
15121522 def __enter__ (self ):
15131523 self ._ensure_valid_state ()
1514-
1515- if not self ._reader :
1516- raise C2paError ("Invalid Reader when entering context" )
1517-
15181524 return self
15191525
15201526 def __exit__ (self , exc_type , exc_val , exc_tb ):
@@ -1532,10 +1538,12 @@ def _ensure_valid_state(self):
15321538 """Ensure the reader is in a valid state for operations.
15331539
15341540 Raises:
1535- C2paError: If the reader is closed or invalid
1541+ C2paError: If the reader is closed, not initialized, or invalid
15361542 """
15371543 if self ._closed :
15381544 raise C2paError (Reader ._ERROR_MESSAGES ['closed_error' ])
1545+ if not self ._initialized :
1546+ raise C2paError ("Reader is not properly initialized" )
15391547 if not self ._reader :
15401548 raise C2paError (Reader ._ERROR_MESSAGES ['closed_error' ])
15411549
@@ -1585,6 +1593,9 @@ def _cleanup_resources(self):
15851593 finally :
15861594 self ._backing_file = None
15871595
1596+ # Reset initialized state after cleanup
1597+ self ._initialized = False
1598+
15881599 except Exception :
15891600 # Ensure we don't raise exceptions during cleanup
15901601 pass
0 commit comments