Today I Learn, Check Attribute Existence in Python Object

It turns out that Dictionary keys are not Object attributes.

Ridho Perdana
Oct 21, 2020 · 2 min read
Image for post
Image for post
Photo by Syd Wachs on Unsplash

In the past week, I and my colleague are learning to use Python programming language at work and decided to write a simple worker with it. The worker is retrieving data from external API with HTTP request and JSON as the response body, if it got success then the data will be stored in our own data storage.

The problem comes when we need to use the cursor, so we can get the next data from the API. The API response will include a cursor field when there is data after the current request. In order to retrieve the next page data, we need to append the cursor to the request’s URL, and we decided to use the cursor field as the identifier.

I google the method about how to check whether an attribute exists in python object and got the result to use Python hasAttribute built-in function. We tried to use that in our function, written like below:

After I tried to run the worker, somehow it always breaks the iteration, even though the cursor field exists within the response object.

Just like many other programmers, the next step to solving that problem is google the solution with a better keyword, this time I search with the keyword: hasattr python not working json object and finally, I got my answer.

It turns out that the dictionary key is not an attribute. The attribute exists within an object created with a Class syntax in Python. So the solution to my problem for checking a key existence inside a dictionary is using a simple in operator.

Finally, my worker can retrieve the next data 😬

Hope this simple note can help you guys solve a similar problem, happy coding!


Easy read, easy understanding.

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store