Introduction to Python INTROSPECTION & FUNCTIONS
A practical guide to exploring Python objects dynamically and writing clean, reusable code.
Why Learn Introspection in Python? Explore Dynamically Examine any object's
Debug with Confidence
attributes and methods at
Quickly identify what an
needed.
saving valuable debugging
runtime 4 no documentation
unfamiliar object can do, time.
Interactive Programming Essential for REPL-driven development and rapid prototyping in the Python shell.
What is Introspection?
Introspection is Python's built-in ability to examine an object's type,
attributes, and methods at runtime 4 without needing to read its source code.
The
dir() Function
The primary tool for introspection 4 returns a sorted list of everything an object exposes.
Runtime Discovery Inspect variables, modules, classes, and instances as your programme runs.
CORE TOOL
Using the
dir() Function
Call dir() on any Python object to instantly reveal its available attributes and methods. 01
02
03
Try it on a string
Works on anything
Explore interactively
dir("Hello") reveals methods like
Pass in variables, modules, classes, or
Use it in the Python shell or a Jupyter
.upper(), .split(), .replace(), and many
more.
built-in types 4 dir() handles them all consistently.
notebook to rapidly discover what an unfamiliar object can do.
Pro tip: Combine dir() with help() to get both the method list and its full documentation in one workflow.
Seeing
dir() in Action Running dir("Hello") in the Python
console outputs a comprehensive list of string methods, including:
.upper() 4 converts to uppercase .split() 4 splits into a list .replace() 4 substitutes characters .strip() 4 removes whitespace Dunder methods (e.g. __len__) are also shown, revealing the object's deeper behaviour.
Defining Functions in Python Functions are the cornerstone of reusable, readable Python code. Instead of repeating logic, you write it once and call it anywhere.
Reusable Blocks
Improved Readability
Write logic once, call it as
Well-named functions make
throughout your programme.
far easier to understand.
many times as needed
code self-documenting and
Basic Syntax Use the def keyword, followed by a name, parentheses, and an
indented body.