Monday, August 25, 2025

🐍INTROSPECTION & UTILITIES

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() and isinstance() when checking inheritance

💡 Try It Yourself

  1. Use dir() on a string and a list.
  2. Check if a variable is an integer using isinstance().
  3. Check if a function is callable using callable().
  4. Print the unique ID of two different variables using id().
  5. Use help() on the sum function to see its documentation.

🖥️ Practice in Browser

No comments:

Post a Comment

🐍What is scikitlearn??