What is Hasattr in Python

Learn if an object has an attribute in Python

In Python, is there any way to tell if an object has an attribute? For example:

How can you tell if the attribute is there before using it?


Try :

EDIT: See the second answer from Linde below for great advice on how to ask for forgiveness! A very pythonic approach!

The general practice in Python is that if the property is likely to be there most of the time, just invoke it and either let the exception pass or catch it with a try / exception block. This will likely be faster than. If the property is likely to be absent most of the time, or if you are unsure, using it is likely faster than repeatedly falling into an exception block.

You can use or intercept, but if you really just want the value of the attribute with a default value when it doesn't exist, the best option is to just use:

I think what you are looking for is this hasattr . However, I would recommend something like this if you can Python properties want to recognize -

The disadvantage here is that it also catches attribute errors in the property code.

Otherwise you do

Docs: http://docs.python.org/library/functions.html
The reason for my recommendation is that hasattr does not recognize any properties.
Link: http://mail.python.org/pipermail/python-dev/2005-December/058498.html

According to pydoc, hasattr (obj, prop) simply calls getattr (obj, prop) and catches exceptions. It is just as valid to provide the attribute access with a try statement and to catch AttributeError as to use hasattr () before.

I would like to suggest avoiding this:

The user @jpalecek mentioned it: if one occurs indoors, you are lost.

Maybe this approach is better:

Depending on the situation, you can check what kind of object you have and then use the appropriate attributes. With the introduction of abstract base classes in Python 2.6 / 3.0, this approach has also become much more powerful (ABCs basically allow a more sophisticated type of duck typing).

One situation where this is useful would be when two different objects have an attribute with the same name but different meanings. Only using it can then lead to strange errors.

A nice example is the distinction between iterators and iterables (see this question). The methods in an iterator and an iterator have the same name, but are semantically very different! So it is useless, but together with ABC it offers a clean solution.

However, I agree that in most situations the approach (described in other answers) is the most appropriate solution.

I hope you are expecting hasattr (), but try to avoid hasattr () and please prefer getattr (). getattr () is faster than hasattr ()

with hasattr ():

the same here i use getattr to get property, if there is no property there is no return

EDIT : This approach has serious limitations. It should work if the object is is iterable . Please check the comments below.

If you Python 3.6 or higher as I use, there is a convenient alternative to check if an object has a certain attribute:

However, I'm not sure which approach is the best right now. Use, use, or use. Comments are welcome.

It is very easy to do. Just use that Object.
This returns a list of all available functions and attributes of the object.

Another possible option, but it depends on what you have before with it mean :


This way you can even search for attributes with no value.

But! Be very careful not to accidentally instantiate and compare multiple locations, as this will never work.

To update:

Based on what I warned about in the paragraph above, since multiple undefined values ​​never match, I recently changed this pattern slightly:

Not to be confused, is a built-in element: it is half the intent of a JS, and you can reuse its definition anywhere, and it will always match. The downsides are that it is "true" in Boolean values ​​and can look strange in logs and stack traces (but you can get over it quickly knowing it only appears in that context).

You can use the built-in method to check whether there are any attributes.

For an instance, if your object is and you want to search for attributes

The method signature itself means that the Attribute, that is passed to the second argument, is Boolean, or corresponds to the presence of an attribute in the object.

is the correct answer. What I want to add is that it can also be used well in conjunction with assert (to avoid unnecessary instructions and make the code more readable):

As stated in another answer to SO: Asserts should be used to test conditions that should never occur. The purpose is to crash prematurely if the program status is damaged.

We use cookies and other tracking technologies to improve your browsing experience on our website, to show you personalized content and targeted ads, to analyze our website traffic, and to understand where our visitors are coming from.

By continuing, you consent to our use of cookies and other tracking technologies and affirm you're at least 16 years old or have consent from a parent or guardian.

You can read details in our Cookie policy and Privacy policy.