Python: retain instance

You can put that code in its own module called reddit

reddit.py:

import praw

reddit = praw.Reddit(client_id='my client id',
                     client_secret='my client secret',
                     user_agent='my user agent')

And then use it like this.

some_other_module.py

import reddit

for submission in reddit.reddit.subreddit('learnpython').hot(limit=10):
    print(submission.title)

Python will only run through the code in the module the first time it is imported, and then it keeps the module around internally so that on future imports the same module is referenced.

A little example you can do to see this is to create the following modules.

a.py

import b # j.x is now 4
import c # j.x is now 9
import j # j.x is still 9
print(j.x) # 9 is printed out

j.py

x = 1

b.py

import j
j.x += 3

c.py

import j
j.x += 5

The number 9 will be printed out because x was only set to 1 the very first time it was imported. Future references to the module where all using the same x.

In your case you could have main.py and tdepend.py import reddit.py, and they would both be using the exact same reddit object.


FYI, you can use the following to see how close you are to reaching Reddit's API limits: praw.models.Auth(reddit).limits().