Fabian
Fabian

Reputation: 407

How do I list all the attributes of an object in Python?

I'm trying to write a Reddit bot using Praw, and this is my function:

submission = reddit.submission(mention.submission.id)

(I have previously defined reddit = praw.Reddit() and whatnot, so submission should give me a submission object.

Firstly, I want to check if the submission is a self post, or a link. I can do that by checking submission.is_self. However, out of curiosity, I tried printing dir(submission) and submission.__dict__, and neither lists is_self as an attribute of the object.

Why is that so? And how can I reliably find all the attributes of the object, without digging into the source code of the library itself? Praw's documentation is a bit lacking in this regard.

Upvotes: 1

Views: 13665

Answers (2)

Adam Solchenberger
Adam Solchenberger

Reputation: 774

The built in dir() method is used to list all attributes:

>>> class MyClass():
...     def __init__(self):
...         self.foo = 1
... 
>>> c = MyClass()
>>> dir(c)
['__doc__', '__init__', '__module__', 'foo']
>>> 

Upvotes: 3

C. Yduqoli
C. Yduqoli

Reputation: 1761

PRAW uses __getattr__ magic to dynamically get and set object attributes (see RedditBase class in praw/models/reddit/base.py). That's why dir() does not show it.

is_self does not exist anywhere in the source code, as this string is based on data received from reddit.

Upvotes: 1

Related Questions