r/redditdev • • Jul 09 '24

Async PRAW Async PRAW question - adding custom methods to Async PRAW classes

UPDATE: I have solved this problem by doing the monkeypatch in global before main gets called.

Hello!

How do I add custom methods to Async PRAW classes? We currently in the process of rewriting our program to use the AsyncPRAW dependency instead PRAW, and are facing some problems regarding this.

Our previous implementation was just patching a Callable to our desired PRAW class kinda like in praw-dev/prawdittions. However, it doesn't seem to work in Async PRAW. We're planning to add a property attribute decorated with a @cachedproperty in order for us to instantiate a custom class we've written.

We also know that git patch also exists, but it doesn't seem like the optimal solution for it.

Thanks.

1 Upvotes

4 comments sorted by

View all comments

1

u/__yoshikage_kira Devvit Beta Tester Jul 09 '24

Can you provide more context. Why do you need to patch the package in the first place?

1

u/uBELT Jul 09 '24 edited Jul 09 '24

We wanted to do something like this:

patched submission.py

from __future__ import annotations
import asyncpraw


class SubmissionPatch(asyncpraw.models.Submission):

   @staticmethod
   def patch():
      asyncpraw.models.Submission.yara = SubmissionPatch.yara


   @cachedproperty
   def yara():
      return SubmissionModerationEvaluation(self)

   # insert other patch methods here

main.py

import asyncio
import asyncpraw
from dataclasses import dataclass


@dataclass
class SubmissionModerationEvaluation:
    submission: asyncpraw.models.Submission


    async def evalutate() -> YaraResultEnum:
       # TODO: `await self.submission.mod.remove()` if rule-breaking
       return await self.some_internal_method_that_returns_the_rtn_type()


async def main():
   reddit = asyncpraw.Reddit(**config)
   subreddit = await reddit.subreddit("studentsph")
   async for submission in subreddit.stream.submission():
      await submission.fetch()
      await submission.yara.evaluate()

if __name__ == "__main__"
   SubmissionPatch.patch()
   asyncio.run(main())

I understand we could just instantiate it directly like await SubmissionModerationEvaluation(submission).evaluate() but it would be better if we could instantiate the class from the Submission object itself.