avatarYang Zhou

Summary

This article outlines three methods for exploring Python objects: checking type information with type(), examining inheritance information using isinstance() and mro(), and listing attributes and methods with dir(), along with getattr(), setattr(), and hasattr() for attribute interaction.

Abstract

The provided content introduces Python developers to efficient ways of inspecting an object when its source code is not readily available or when time constraints prevent a thorough code review. The first method involves using the type() function to determine the type of an object, which can be compared to other types or checked against more complex types using the types module. The second method utilizes isinstance() to verify an object's inheritance from a particular class or a tuple of classes, and mro() to view the entire inheritance chain. Lastly, the dir() function is presented as a means to list all attributes and methods of an object, with getattr(), setattr(), and hasattr() providing further functionality to interact with these attributes and methods, including setting default values to prevent errors when accessing non-existent attributes.

Opinions

  • The author emphasizes the practicality of these methods when dealing with objects from APIs or when time is limited.
  • The use of type() is recommended for basic type checking, while the types module is suggested for more nuanced type comparisons.
  • isinstance() is highlighted as a convenient tool for checking inheritance relationships, especially with the ability to pass a tuple of types.
  • The mro() method is acknowledged as a comprehensive way to understand the full inheritance hierarchy of a class, with credit given to Dmitri Fidiriuc for reminding the author of this method.
  • The dir() function is presented as a straightforward way to get an overview of an object's attributes and methods, but the author notes that it only provides names and does not offer deeper insights into the object's functionality.
  • The author advises using getattr() with a default value to avoid AttributeError when attempting to access attributes that may not exist.
  • The article concludes by reiterating the utility of these built-in functions for gaining quick insights into an object's structure and behavior, suggesting that they are particularly useful when direct access to an object's information is not possible.

3 Ways to Explore a Python Object

Photo by James Harrison on Unsplash

Introduction

When we get a reference of a Python object, how can we know the information about it? Of course, we can read its source code. However, sometimes we don’t have enough time to read it or even we just get this object from an API and cannot access its source code.

This post will introduce three ways to have a quick check of a Python object.

1. Get the Type Information of Objects

First of all, when we get an object, we can check which type it belongs to by type() method.

Since the type() method returns an object’s type, it can be used to compared two types.

Note: In the above example, we compared type(b)==int and got a True. If we compare type(b)==type(int), a False will be printed. Because the type of int is type.

print(type(int))
# <class 'type'>

With the help of the types module, we can check more complex types:

2. Get Inheritance Information of Classes

Check it is an Instance or Not

For inherited classes, using the isinstance() method is a very convenient way to check their inheritance relationship.

As the above example shown, the isinstance() method checks whether an object is an instance of a class or of a subclass thereof.

The second parameter of isinstance() method can be a tuple to help us judge whether an object is one of certain types.

Get the Whole Chain of Inheritance

Type’s method mro() can give us the whole chain of class inheritance relations.(Thanks Dmitri Fidiriuc for reminding me this method.)

3. Get all Attributes and Methods of Objects

The dir() method, which returns a list containing strings, can help us get all names of attributes and methods within an object.

Only names? Obviously, it’s not enough. 😃

With the help of these three methods: getattr(), setattr() and hasattr(), we are able to get, set and check attributes or methods of an object.

Note: If we use getattr() to acquire a nonexistent attribute or method, an AttributeError will be raised. Therefore, we can set a default value as the third parameter to avoid this error.

As we mentioned in the introduction section, we get the information of an object by these ways when it’s hard to get it directly. If we can get the information by Yang.sex directly, there is no need to use the method getattr(Yang,'sex').

Conclusion

Through a series of built-in functions, we can analyze a Python object and get its internal information. These methods are really useful to get a quick look of an object.

Thanks for reading! More relative Python tutorials :

Programming
Python
Python3
Python Programming
Programming Languages
Recommended from ReadMedium