Today I Learn, Check Attribute Existence in Python Object
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
Finally, my worker can retrieve the next data 😬
Hope this simple note can help you guys solve a similar problem, happy coding!