When developing in Python, you often want to check what methods a library object has, or determine if a specific variable exists in a dynamically generated object. To perform this kind of “Object Introspection,” Python provides two convenient built-in functions: dir() and hasattr().
This article explains the functions of these two tools and their respective use cases.
1. dir() Function: Listing All Attributes
The dir() function returns a list of strings representing the names of “all attributes (variables and methods)” held by the object passed as an argument. It is mainly used during debugging or when exploring the capabilities of an object in interactive mode.
Specific Usage Example
As an example, let’s create a class representing a game player and check what attributes its instance has.
class GamePlayer:
def __init__(self, name, level):
self.name = name
self.level = level
def attack(self):
print(f"{self.name} attacks!")
# Instantiation
player = GamePlayer("Hero", 50)
# Get list of attributes
attributes = dir(player)
print(attributes)
Output (Excerpt):
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', ..., '__init__', ..., 'attack', 'level', 'name']
The output list includes not only the name, level, and attack defined by you, but also special methods automatically added by Python (those surrounded by double underscores, like __init__ and __class__). This allows you to comprehensively grasp all functions and data held by the object.
2. hasattr() Function: Checking for the Existence of a Specific Attribute
The hasattr() function checks whether a “specifically named attribute” exists within an object and returns True or False.
Syntax:
hasattr(object, "attribute_name")
It is very effective when you want to determine the presence of an attribute dynamically during program execution and branch processing accordingly.
Specific Usage Example
Let’s check if specific attributes exist for the player instance created earlier.
# Is there a 'name' attribute?
print(f"Has 'name'?: {hasattr(player, 'name')}")
# Is there an 'mp' (Magic Point) attribute?
print(f"Has 'mp'?: {hasattr(player, 'mp')}")
# Is there an 'attack' method?
print(f"Has 'attack'?: {hasattr(player, 'attack')}")
Output:
Has 'name'?: True
Has 'mp'?: False
Has 'attack'?: True
Practical Branching
Using hasattr() allows you to write safe code that accesses an attribute only if it exists.
# If 'mp' exists, cast a spell; otherwise, perform a physical attack
if hasattr(player, "mp"):
print("Cast a spell!")
else:
print("No MP, performing physical attack.")
player.attack()
Output:
No MP, performing physical attack.
Hero attacks!
In this way, you can prevent an AttributeError (an error indicating the attribute does not exist) before it happens.
Summary
dir(obj): Retrieves a list of all attribute names held by the object. Primarily used for debugging and exploration purposes.hasattr(obj, "name"): Checks if a specific attribute exists using a boolean value. Used for conditional branching and error avoidance within a program.
