Python provides built-in functions to examine objects, check properties, and explore your code interactively. This is called introspection.
What is Introspection?
Introspection is the ability of a program to examine the type or properties of objects at runtime. Python provides several built-in functions for introspection.
Common Built-in Introspection & Utility Functions
# dir(): lists attributes and methods of an object
print(dir(list))
# type(): returns type of object
x = 10
print(type(x))
# isinstance(): checks if object is of a certain type
print(isinstance(x, int)) # True
# callable(): checks if object can be called (like functions)
def greet():
print("Hello!")
print(callable(greet)) # True
print(callable(x)) # False
# id(): returns unique ID of object in memory
print(id(x))
# help(): shows documentation of object or function
help(len)
Common Mistakes
- Calling
dir()on an undefined variable →NameError - Forgetting parentheses for
callable()→ returns object info, not evaluation - Using
help()incorrectly without an object → opens interactive help unexpectedly - Confusing
type()andisinstance()when checking inheritance
💡 Try It Yourself
- Use
dir()on a string and a list. - Check if a variable is an integer using
isinstance(). - Check if a function is callable using
callable(). - Print the unique ID of two different variables using
id(). - Use
help()on thesumfunction to see its documentation.
No comments:
Post a Comment