hasattr(object, string) function takes an
object and a
string as an input. It returns
True if one of the
object‘s attributes has the name given by the
string. Otherwise, it returns
hasattr() object has the following syntax:
hasattr(object, attribute) # Does the object have this attribute?
|Arguments||The object from which the attribute value should be drawn.|
|The attribute name as a string.|
|Return Value||Returns Boolean whether the |
hasattr(object, attribute) method returns
True, if the object has the attribute and
Learn by example! Here’s an example on how to use the
hasattr() built-in function.
# Define class with one attribute class Car: def __init__(self, brand): self.brand = brand # Create object porsche = Car('porsche') # Check if porsche has attributes print('Porsche has attribute "brand": ', hasattr(porsche, 'brand')) print('Porsche has attribute "color": ', hasattr(porsche, 'color'))
The output of this code snippet is:
Porsche has attribute "brand": True Porsche has attribute "color": False
It has the attribute “brand” but not the attribute “color”.
Why? Nine Practical Use Cases of Python’s hasattr() Function
- Error Handling: You can use
hasattr()to avoid accessing errors when trying to access an attribute of a dynamic object.
- Ternary Operator: You can use
hasattr()in a ternary operator to conditionally assign a value to a variable such as in:
age = object.age if hasattr(object, 'age') else 0. However, be careful when using
hasattr()as it always return
False, no matter the error message. Thus, it may overshadow an error different to the error that appears if the attribute doesn’t exist. So, the attribute may indeed exist but if trying to access it causes an error, the result will be
- Dynamic Attribute Access: Checking if an object has a certain attribute dynamically, useful in cases where attribute names are determined at runtime.
- Preventing Runtime Errors: Avoiding
AttributeErrorby checking for attribute existence before attempting to access it.
- Custom Error Handling: Implementing custom error handling or logging when an expected attribute is missing from an object.
- Adaptive Code Execution: Adapting code behavior based on the presence or absence of certain attributes in objects.
- Feature Detection: Detecting if a particular feature or method is available in an object, especially useful when working with third-party libraries or APIs.
- Attribute-based Dispatch: Dispatching to different code paths based on which attributes an object has or lacks.
- Introspection and Debugging: Inspecting objects during debugging to understand their capabilities or to generate informative debug outputs.
Frequently Asked Questions (FAQs)
How Does hasattr() Function Check Attributes in Object’s Class and Its Superclasses?
hasattr() function in Python is used to determine whether an object has a named attribute. It takes two arguments: the object and a string representing the name of the attribute you are checking for.
Here’s how the process works:
- Local Attributes Check: Initially,
hasattr()checks whether the specified attribute name exists in the namespace of the object itself.
- Inheritance Check (Including Superclasses): If the attribute is not found in the local namespace,
hasattr()will proceed to check in the namespaces of any superclasses from which the object’s class inherits, following the method resolution order (MRO). This way, it can detect attributes inherited from superclasses.
- Descriptor Protocol: If the class has defined
__getattribute__()methods, these methods are invoked as part of the attribute lookup process. If these methods raise an
False; otherwise, it will return
hasattr() provides a comprehensive check for attribute presence, encompassing both the local class namespace and inherited namespaces from superclasses.
This behavior ensures that
hasattr() can accurately reflect the attribute lookup process that Python would perform during regular attribute access, making it a reliable tool for introspective operations in your code.
If you want to learn more about namespaces, feel free to read our tutorial and watch the associated video:
🧑💻 Recommended: Understanding Namespaces in Python
What is the
hasattr() function used for in Python?
hasattr() function is handy for checking if a particular object has a given named attribute before attempting to access it. This can prevent runtime errors that would occur if you tried to access an attribute that doesn’t exist. Here’s how you’d use it:
class Dog: def __init__(self, name): self.name = name fido = Dog('Fido') # Check if fido has a 'name' attribute print(hasattr(fido, 'name')) # Output: True # Check if fido has a 'bark' attribute print(hasattr(fido, 'bark')) # Output: False
hasattr() differ from
hasattr() checks if an object has a certain attribute,
getattr() attempts to retrieve the value of that attribute. If the attribute doesn’t exist,
getattr() will raise an
AttributeError, unless a default value is provided as a third argument. Here’s a comparison:
class Cat: def __init__(self, name): self.name = name whiskers = Cat('Whiskers') # Using hasattr() print(hasattr(whiskers, 'name')) # Output: True print(hasattr(whiskers, 'meow')) # Output: False # Using getattr() print(getattr(whiskers, 'name')) # Output: 'Whiskers' print(getattr(whiskers, 'meow', 'default_value')) # Output: 'default_value'
hasattr() check for method existence?
hasattr() can be used to check if an object has a specific method. Methods are just attributes that are callable. Here’s a simple example:
class Bird: def chirp(self): print('Chirp chirp!') tweety = Bird() # Check if tweety has a 'chirp' method print(hasattr(tweety, 'chirp')) # Output: True
What happens with
hasattr() if an attribute is set to
Even if an attribute is set to
hasattr() will still return
True, as the attribute does exist on the object—it just has a value of
None. Here’s an illustration:
class Fish: def __init__(self, name=None): self.name = name nemo = Fish() # Check if nemo has a 'name' attribute print(hasattr(nemo, 'name')) # Output: True
getattr()function returns the value of an attribute.
setattr()function changes the value of an attribute.
hasattr()function checks if an attribute exists.
delattr()function deletes an existing attribute.
hasattr(object, string) function takes an
object and a
string as an input.
- It returns
Trueif one of the
object‘s attributes has the name given by
- It returns
Falseotherwise if one of the
object‘s attributes doesn’t have the name given by
>>> hasattr('hello', 'count') True >>> hasattr('hello', 'xxx') False
hasattr() also returns
True if the string is the name of a method rather than an attribute.
I hope you enjoyed the article! To improve your Python education, you may want to join the popular free Finxter Email Academy:
Do you want to boost your Python skills in a fun and easy-to-consume way? Consider the following resources and become a master coder!
While working as a researcher in distributed systems, Dr. Christian Mayer found his love for teaching computer science students.
To help students reach higher levels of Python success, he founded the programming education website Finxter.com that has taught exponential skills to millions of coders worldwide. He’s the author of the best-selling programming books Python One-Liners (NoStarch 2020), The Art of Clean Code (NoStarch 2022), and The Book of Dash (NoStarch 2022). Chris also coauthored the Coffee Break Python series of self-published books. He’s a computer science enthusiast, freelancer, and owner of one of the top 10 largest Python blogs worldwide.
His passions are writing, reading, and coding. But his greatest passion is to serve aspiring coders through Finxter and help them to boost their skills. You can join his free email academy here.