from — Intermediate Playground
Used with import to bring in specific names from a module
Python Playground
class ConfigError(Exception):
pass
def load_config(path):
try:
raise FileNotFoundError(f"No file: {path}")
except FileNotFoundError as e:
raise ConfigError("Failed to load config") from e
try:
load_config("settings.yaml")
except ConfigError as e:
print(f"Error: {e}")
print(f"Cause: {e.__cause__}")
print(f"Cause type: {type(e.__cause__).__name__}")
# Suppress context with 'from None'
def clean_error():
try:
int("abc")
except ValueError:
raise TypeError("Expected numeric string") from None
try:
clean_error()
except TypeError as e:
print(f"\nClean error: {e}")
print(f"Cause: {e.__cause__}")
print(f"Context suppressed: {e.__suppress_context__}")
Output
Click "Run" to execute your code
'raise X from Y' sets __cause__ for clear error chains. 'raise X from None' suppresses the implicit chaining context.
Challenge
Try modifying the code above to explore different behaviors. Can you extend the example to handle a new use case?