def — Expert Examples
Defines a new function or method
Function objects and introspection
Examining function internals.
python
def example(x: int, y: str = "hello") -> bool: """An example function.""" z = x + len(y) return z > 10 import dis import inspect # Signature sig = inspect.signature(example) print(f"Signature: {sig}") # Annotations print(f"Annotations: {example.__annotations__}") # Code object code = example.__code__ print(f"Variables: {code.co_varnames}") print(f"Constants: {code.co_consts}") # Bytecode print(f"\nBytecode:") dis.dis(example)
Functions are first-class objects with rich metadata: __code__ holds the compiled bytecode, __annotations__ holds type hints, and __doc__ holds the docstring. The dis module shows the bytecode instructions.
Want to try these examples interactively?
Open Expert Playground