fromIntermediate Examples

Used with import to bring in specific names from a module

from in exception chaining

Using 'raise X from Y' for explicit exception chaining.

python
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__}")

'raise X from Y' sets __cause__ for clear error chains. 'raise X from None' suppresses the implicit chaining context.

from for relative imports

Using from with dots for package-relative imports.

python
# Absolute import (most common)
# from mypackage.utils import helper

# Relative imports (inside packages)
# from . import sibling_module
# from .. import parent_module
# from .utils import helper

# Simulating the concept
print("Import styles:")
print("  from math import sqrt        # absolute, specific")
print("  from . import utils           # relative, current package")
print("  from .. import config          # relative, parent package")
print("  from .sub.mod import func     # relative, sub-package")

# Star imports (use sparingly)
# from math import *  # imports everything in __all__
import math
print(f"\nmath.__all__ has {len(dir(math))} names")

Relative imports use dots: '.' is current package, '..' is parent. Star imports bring in everything from __all__. Avoid star imports except in __init__.py or interactive sessions.

Want to try these examples interactively?

Open Intermediate Playground