Inspect available attribute names with the built-in dir() function.
What You Will Learn
dir(value) returns a sorted list of names supplied by the object’s introspection machinery, often including inherited and special attributes. It is useful for exploration but is not a complete contract for dynamic attributes.
Use help() and official docs for supported method behavior, not dir() alone.
Step-by-Step Example
The example below makes the behavior visible with small input values that you can change safely.
class Monitor:
def check(self):
return True
monitor = Monitor()
print("check" in dir(monitor))
print("__class__" in dir(monitor))
How the Example Works
- The class Monitor groups data and behavior; its methods run when called on an instance.
- The variable monitor holds the result of Monitor(). Later lines use that value or inspect how it changes.
- The print() calls make the return values or state visible so you can compare them with the explanation and check your prediction.
Expected output from the example:
True
True
Another Example: Compare the Results
Try a second input and compare it with the first. Notice whether the result changes in type, value, order, or number of items.
print("upper" in dir("sample"))
print("missing" in dir("sample"))
Expected output:
True
False
When You Would Use This
These tools are useful when composing small reusable functions, adapting callbacks, or eliminating repeated work. Pay attention to whether the operation returns a new object, updates state, or produces lazy results. Test a small success case and a boundary case before integrating it into an application.
Practice: Modify the Code
Find the names of public methods on a toy class.
Verify the changed output against the behavior described above, including the relevant invalid or boundary case.
For complete parameters and version details, consult the official Python documentation.
Common Beginner Mistakes
- Assuming every name from dir() is public, stable, and safe to call.
- Treating absence from dir() as proof that dynamic lookup cannot succeed.
Key Takeaways
- Inspect available attribute names with the built-in dir() function.
- dir(value) returns a sorted list of names supplied by the object’s introspection machinery, often including inherited and special attributes.
- Use help() and official docs for supported method behavior, not dir() alone.