Python is attribute exist

How to Check if an Object has an Attribute in Python

Since everything in Python is an object and objects have attributes (fields and methods), it’s natural to write programs that can inspect what kind of attributes an object has. For example, a Python program could open a socket on the server and it accepts Python scripts sent over the network from a client machine. Upon receiving a new script, the server-side Python program can inspect or more precisely introspect objects, modules, and functions in the new script to decide how to perform the function, log the result, and various useful tasks.

hasattr vs. try-except

There’re two ways to check if a Python object has an attribute or not. The first way is to call the built-in function hasattr(object, name) , which returns True if the string name is the name of one of the object ‘s attributes, False if not. The second way is to try to access an attribute in an object and perform some other function if an AttributeError was raised.

Читайте также:  Php ext php openssl dll
[python]
>>> hasattr(‘abc’, ‘upper’)
True
>>> hasattr(‘abc’, ‘lower’)
True
>>> hasattr(‘abc’, ‘convert’)
False
[/python] [python]
>>> try:
. ‘abc’.upper()
. except AttributeError:
. print(«abc does not have attribute ‘upper'»)
.
‘ABC’
>>> try:
. ‘abc’.convert()
. except AttributeError:
. print(«abc does not have attribute ‘convert'»)
.
abc does not have attribute ‘convert’
[/python]

What’s the difference between these two styles? hasattr is often referred as a Python programming style called «Look Before You Leap» (LBYL) because you check whether an object has an attribute or not before you access it. While try-except is referred as «Easier to Ask for Forgiveness than Permission» (EAFP) because you try the attribute access first and ask for forgiveness in the except block instead of asking for permission like hasattr .

Which way is better, then? Well, both doctrines have loyal supporters and both styles seem to be well-versed to deal with any real-world programming challenge. Sometimes, it makes sense to use LBYL if you want to make sure an attribute definitely exists and stop execution if it doesn’t. For example, you know for certain at a point in the program that a passed-in object should have a valid file pointer attribute on which the following code can work. On the other hand, it also makes sense to use EAFP if you know an attribute might not exist at some point during the program’s execution. For example, a music player could not guarantee a MP3 file is always on-disk at the same location, because it might be deleted, modified, or moved by the user at any time. In this case, the music player can try to access the MP3 file first and notify the user that the file does not exist in an except block.

Читайте также:  Java file could not be launched

hasattr vs __dict__

Although hasattr is a built-in function that is designed to check if an attribute exists in an object, sometimes it might be more accurate to check an object’s __dict__ for an attribute’s existence instead due to the fact that hasattr does not care about the reason why an attribute’s attached to an object while you may want to know why an attribute’s attached to an object. For example, an attribute might be attached to an object due to its parent class instead of the object itself.

[python]
>>> class A(object):
. foo = 1
.
>>> class B(A):
. pass
.
>>> b = B()
>>> hasattr(b, ‘foo’)
True
>>> ‘foo’ in b.__dict__
False
[/python]

In the previous code, since class B is a subclass of class A , class B also has the attribute «foo». However, because «foo» is inherited from A , B.__dict__ does not contain it. Sometimes, it might be crucial to know whether an attribute comes from an object’s class itself or from the objects’ superclass.

Tips and Suggestions

When I see a bird that walks like a duck and swims like a duck and quacks like a duck, I call that bird a duck.

Once you’ve learnt how to check if an object has an attribute in Python, checkout how to get an attribute from an object.

About The Author

Xiaonuo Gantan

Xiaonuo Gantan

Xiaonuo loves writing Python programs to solve problems and implement systems. His research and work interests include data mining, web server architecture and relational or document-based database systems.

Источник

Simple Ways to Check if an Object has Attribute in Python

python check if object has attribute

Python is an object-oriented programming language, has the main emphasis on objects. Objects represent the real-world entities inside a class. A class acts as a blueprint for the object. It consists of data, i.e., variables and functions which act on that data. A class is a template consisting of the object’s variables and functions. Attributes contain information about an object. In this article, we shall be looking at how in python we can check if object has attribute.

What are attributes?

Attributes in a class are the variables that are shared among all the instances of a given class. With these attributes, we can describe characteristics for the class. Each instance in a class shall have the same value for each attribute.

Let us consider a class named ‘Sample.’ The class has an attribute named ‘var,’ which has a string value ‘Value1’. Then, we created two objects of the class – ‘obj1’ and ‘obj2’. Next, we shall print the attribute ‘var’ for both objects.

class Sample: var = 'Value1' obj1 = Sample() obj2 = Sample() print(obj1.var) print(obj2.var)

The output printed shall be the same for both the objects signifying that all the instances will have the same value for attributes.

Python Check If Object Has Attribute Using hasattr()

To check if an object in python has a given attribute, we can use the hasattr() function.

The syntax of the hasattr() function is:

The function accepts the object’s name as the first argument ‘object’ and the name of the attribute as the second argument ‘name.’ It returns a boolean value as the function output. It shall return ‘True’ if the attribute is present in the object and ‘False’ if the object does not contain that attribute.

Let us understand the use of the hasattr() function with an example. We shall first define a class named ‘Book’. The class Book consists of three attributes – ‘book_name’, ‘author_name’ and ‘publishing_year’. Here ‘book_name’ and ‘author_name’ store string values whereas ‘publishing_year’ stores integer value.

class Book: book_name = 'Digital Fortress' author_name = 'Dan Brown' publishing_year = 1998

After creating the class, we shall create an object for the same class named ‘obj1’.

Now, we shall use the hasattr() function. We will pass the object name ‘obj1’ as the first argument to the function and the attribute name ‘book_name’ as the second argument to the function. Then, we shall print the output of the hasattr() function.

print(hasattr(obj1,'book_name'))

The output will be ‘True’ because the attribute exists.

If we try to print an attribute name that does not exist , the function will output ‘False’.

print(hasattr(obj1,'no_of_pages'))

If we try to pass an object ‘obj2’ which does not exist, then the function value will be ‘False’ even if the attribute of the given name exists.

print(hasattr(obj2,'book_name'))

The Entire Code is:

class Book: book_name = 'Digital Fortress' author_name = 'Dan Brown' publishing_year = 1998 obj1 = Book() print(hasattr(obj1,'book_name')) print(hasattr(obj1,'no_of_pages')) print(hasattr(obj2,'book_name'))

Python Check If Object Has Attribute using getattr()

We can also use another method named getattr() to check if an object has an attribute or not. We can achieve this by including the function in a try-except block. That is how to hasattr() function also works in python. It implements the getattr() function, and if it throws an AttributeError, it shall execute the except block.

The syntax of the getattr() function is :

getattr(object, name[, default])

As the first argument, it accepts is the name of the object whose attributes have to be found. The second argument is the name of the attribute for the given object. Finally, it accepts a default argument which will be printed if the attribute does not exist. If the attribute exists in a given object, the getattr() shall return the value stored by the attribute. If it does not exist, it shall throw an attribute error .

Let us look at two ways of using the getattr() function to check if an object has an attribute.

Using the default argument

The getattr() function shall throw an AttributeError if the attribute does not exist. But if we specify a default argument as the third argument to the getattr() function, then that argument will be printed.

Let us take the same class ‘Book’ as taken in the above example. Now, we shall try to print an attribute which does not exist.

class Book: book_name = 'Digital Fortress' author_name = 'Dan Brown' publishing_year = 1998 obj1 = Book() print(getattr(obj1,'no_of _pages'))

Since the attribute is not present, it throws AttributeError.

AttributeError: 'Book' object has no attribute 'no_of _pages'

But, if we specify a default argument, then instead of throwing error, it will print that.

class Book: book_name = 'Digital Fortress' author_name = 'Dan Brown' publishing_year = 1998 obj1 = Book() print(getattr(obj1,'no_of _pages','Attribute does not exist'))

Using the try catch block

We can also use a try-catch block to check if the attribute exists or not. We shall pass the getattr() function inside the try block. If the attribute exists, it will simply print the attribute’s value.

But, if it does not, then it shall throw an AttributeError. So then, we shall catch the AttributeError in the except block and print a statement saying that the attribute does not exist.

class Book: book_name = 'Digital Fortress' author_name = 'Dan Brown' publishing_year = 1998 obj1 = Book() try: print(getattr(obj1,'no_of_pages')) except AttributeError: print("Attribute does not exist")

Python Check If Object Has Attribute using if else block

We can also use an if-else block for checking if the attribute exists or not. If the attribute exists, the hasattr() function shall return True, and the if block shall be executed, thereby printing the value of that attribute. But, if the attribute does not exist, then hasattr() shall return False, and the else part will be executed.

class Book: book_name = 'Digital Fortress' author_name = 'Dan Brown' publishing_year = 1998 obj1 = Book() if hasattr(obj1, 'book_name'): print(obj1.book_name) else: print('Attribute does not exist')

Since the attribute exists, it shall print the name of the book.

That is all for checking in python if an object exists or not. If you have any doubts in mind, do let us know in the comments below.

Until next time, Keep Learning!

Источник

Оцените статью