Skip to content

Commit

Permalink
Merge pull request #1929 from praw-dev/sort_code
Browse files Browse the repository at this point in the history
Sort code to adhere to contributing guidelines
  • Loading branch information
LilSpazJoekp committed Dec 26, 2022
2 parents a5e8176 + 9a3f934 commit fd5741b
Show file tree
Hide file tree
Showing 32 changed files with 3,454 additions and 3,454 deletions.
224 changes: 112 additions & 112 deletions praw/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,16 @@ def error_message(self) -> str:
error_str += f" on field {self.field!r}"
return error_str

def __eq__(self, other: Union["RedditErrorItem", List[str]]):
"""Check for equality."""
if isinstance(other, RedditErrorItem):
return (self.error_type, self.message, self.field) == (
other.error_type,
other.message,
other.field,
)
return super().__eq__(other)

@_deprecate_args("error_type", "message", "field")
def __init__(
self,
Expand All @@ -49,16 +59,6 @@ def __init__(
self.message = message
self.field = field

def __eq__(self, other: Union["RedditErrorItem", List[str]]):
"""Check for equality."""
if isinstance(other, RedditErrorItem):
return (self.error_type, self.message, self.field) == (
other.error_type,
other.message,
other.field,
)
return super().__eq__(other)

def __repr__(self) -> str:
"""Return an object initialization representation of the instance."""
return (
Expand All @@ -71,108 +71,6 @@ def __str__(self):
return self.error_message


class APIException(PRAWException):
"""Old class preserved for alias purposes.
.. deprecated:: 7.0
Class :class:`.APIException` has been deprecated in favor of
:class:`.RedditAPIException`. This class will be removed in PRAW 8.0.
"""

@staticmethod
def parse_exception_list(exceptions: List[Union[RedditErrorItem, List[str]]]):
"""Covert an exception list into a :class:`.RedditErrorItem` list."""
return [
exception
if isinstance(exception, RedditErrorItem)
else RedditErrorItem(
error_type=exception[0],
field=exception[2] if bool(exception[2]) else "",
message=exception[1] if bool(exception[1]) else "",
)
for exception in exceptions
]

@property
def error_type(self) -> str:
"""Get error_type.
.. deprecated:: 7.0
Accessing attributes through instances of :class:`.RedditAPIException` is
deprecated. This behavior will be removed in PRAW 8.0. Check out the
:ref:`PRAW 7 Migration tutorial <Exception_Handling>` on how to migrate code
from this behavior.
"""
return self._get_old_attr("error_type")

@property
def message(self) -> str:
"""Get message.
.. deprecated:: 7.0
Accessing attributes through instances of :class:`.RedditAPIException` is
deprecated. This behavior will be removed in PRAW 8.0. Check out the
:ref:`PRAW 7 Migration tutorial <Exception_Handling>` on how to migrate code
from this behavior.
"""
return self._get_old_attr("message")

@property
def field(self) -> str:
"""Get field.
.. deprecated:: 7.0
Accessing attributes through instances of :class:`.RedditAPIException` is
deprecated. This behavior will be removed in PRAW 8.0. Check out the
:ref:`PRAW 7 Migration tutorial <Exception_Handling>` on how to migrate code
from this behavior.
"""
return self._get_old_attr("field")

def _get_old_attr(self, attrname):
warn(
f"Accessing attribute '{attrname}' through APIException is deprecated."
" This behavior will be removed in PRAW 8.0. Check out"
" https://praw.readthedocs.io/en/latest/package_info/praw7_migration.html"
" to learn how to migrate your code.",
category=DeprecationWarning,
stacklevel=3,
)
return getattr(self.items[0], attrname)

def __init__(
self,
items: Union[List[Union[RedditErrorItem, List[str], str]], str],
*optional_args: str,
):
"""Initialize a :class:`.RedditAPIException` instance.
:param items: Either a list of instances of :class:`.RedditErrorItem` or a list
containing lists of unformed errors.
:param optional_args: Takes the second and third arguments that
:class:`.APIException` used to take.
"""
if isinstance(items, str):
items = [[items, *optional_args]]
elif isinstance(items, list) and isinstance(items[0], str):
items = [items]
self.items = self.parse_exception_list(items)
super().__init__(*self.items)


class RedditAPIException(APIException):
"""Container for error messages from Reddit's API."""


class ClientException(PRAWException):
"""Indicate exceptions that don't involve interaction with Reddit's API."""

Expand Down Expand Up @@ -298,3 +196,105 @@ def __init__(self):
" your local machine.",
None,
)


class APIException(PRAWException):
"""Old class preserved for alias purposes.
.. deprecated:: 7.0
Class :class:`.APIException` has been deprecated in favor of
:class:`.RedditAPIException`. This class will be removed in PRAW 8.0.
"""

@staticmethod
def parse_exception_list(exceptions: List[Union[RedditErrorItem, List[str]]]):
"""Covert an exception list into a :class:`.RedditErrorItem` list."""
return [
exception
if isinstance(exception, RedditErrorItem)
else RedditErrorItem(
error_type=exception[0],
field=exception[2] if bool(exception[2]) else "",
message=exception[1] if bool(exception[1]) else "",
)
for exception in exceptions
]

@property
def error_type(self) -> str:
"""Get error_type.
.. deprecated:: 7.0
Accessing attributes through instances of :class:`.RedditAPIException` is
deprecated. This behavior will be removed in PRAW 8.0. Check out the
:ref:`PRAW 7 Migration tutorial <Exception_Handling>` on how to migrate code
from this behavior.
"""
return self._get_old_attr("error_type")

@property
def field(self) -> str:
"""Get field.
.. deprecated:: 7.0
Accessing attributes through instances of :class:`.RedditAPIException` is
deprecated. This behavior will be removed in PRAW 8.0. Check out the
:ref:`PRAW 7 Migration tutorial <Exception_Handling>` on how to migrate code
from this behavior.
"""
return self._get_old_attr("field")

@property
def message(self) -> str:
"""Get message.
.. deprecated:: 7.0
Accessing attributes through instances of :class:`.RedditAPIException` is
deprecated. This behavior will be removed in PRAW 8.0. Check out the
:ref:`PRAW 7 Migration tutorial <Exception_Handling>` on how to migrate code
from this behavior.
"""
return self._get_old_attr("message")

def __init__(
self,
items: Union[List[Union[RedditErrorItem, List[str], str]], str],
*optional_args: str,
):
"""Initialize a :class:`.RedditAPIException` instance.
:param items: Either a list of instances of :class:`.RedditErrorItem` or a list
containing lists of unformed errors.
:param optional_args: Takes the second and third arguments that
:class:`.APIException` used to take.
"""
if isinstance(items, str):
items = [[items, *optional_args]]
elif isinstance(items, list) and isinstance(items[0], str):
items = [items]
self.items = self.parse_exception_list(items)
super().__init__(*self.items)

def _get_old_attr(self, attrname):
warn(
f"Accessing attribute '{attrname}' through APIException is deprecated."
" This behavior will be removed in PRAW 8.0. Check out"
" https://praw.readthedocs.io/en/latest/package_info/praw7_migration.html"
" to learn how to migrate your code.",
category=DeprecationWarning,
stacklevel=3,
)
return getattr(self.items[0], attrname)


class RedditAPIException(APIException):
"""Container for error messages from Reddit's API."""
62 changes: 31 additions & 31 deletions praw/models/helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,37 @@ def __call__(
"""
return LiveThread(self._reddit, id=id)

@_deprecate_args("title", "description", "nsfw", "resources")
def create(
self,
title: str,
*,
description: Optional[str] = None,
nsfw: bool = False,
resources: str = None,
) -> "praw.models.LiveThread":
"""Create a new :class:`.LiveThread`.
:param title: The title of the new :class:`.LiveThread`.
:param description: The new :class:`.LiveThread`'s description.
:param nsfw: Indicate whether this thread is not safe for work (default:
``False``).
:param resources: Markdown formatted information that is useful for the
:class:`.LiveThread`.
:returns: The new :class:`.LiveThread` object.
"""
return self._reddit.post(
API_PATH["livecreate"],
data={
"description": description,
"nsfw": nsfw,
"resources": resources,
"title": title,
},
)

def info(self, ids: List[str]) -> Generator["praw.models.LiveThread", None, None]:
"""Fetch information about each live thread in ``ids``.
Expand Down Expand Up @@ -188,37 +219,6 @@ def generator():

return generator()

@_deprecate_args("title", "description", "nsfw", "resources")
def create(
self,
title: str,
*,
description: Optional[str] = None,
nsfw: bool = False,
resources: str = None,
) -> "praw.models.LiveThread":
"""Create a new :class:`.LiveThread`.
:param title: The title of the new :class:`.LiveThread`.
:param description: The new :class:`.LiveThread`'s description.
:param nsfw: Indicate whether this thread is not safe for work (default:
``False``).
:param resources: Markdown formatted information that is useful for the
:class:`.LiveThread`.
:returns: The new :class:`.LiveThread` object.
"""
return self._reddit.post(
API_PATH["livecreate"],
data={
"description": description,
"nsfw": nsfw,
"resources": resources,
"title": title,
},
)

def now(self) -> Optional["praw.models.LiveThread"]:
"""Get the currently featured live thread.
Expand Down
16 changes: 8 additions & 8 deletions praw/models/list/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,14 @@ class BaseList(PRAWBase):

CHILD_ATTRIBUTE = None

def __contains__(self, item: Any) -> bool:
"""Test if item exists in the list."""
return item in getattr(self, self.CHILD_ATTRIBUTE)

def __getitem__(self, index: int) -> Any:
"""Return the item at position index in the list."""
return getattr(self, self.CHILD_ATTRIBUTE)[index]

def __init__(self, reddit: "praw.Reddit", _data: Dict[str, Any]):
"""Initialize a :class:`.BaseList` instance.
Expand All @@ -27,14 +35,6 @@ def __init__(self, reddit: "praw.Reddit", _data: Dict[str, Any]):
for index, item in enumerate(child_list):
child_list[index] = reddit._objector.objectify(item)

def __contains__(self, item: Any) -> bool:
"""Test if item exists in the list."""
return item in getattr(self, self.CHILD_ATTRIBUTE)

def __getitem__(self, index: int) -> Any:
"""Return the item at position index in the list."""
return getattr(self, self.CHILD_ATTRIBUTE)[index]

def __iter__(self) -> Iterator[Any]:
"""Return an iterator to the list."""
return getattr(self, self.CHILD_ATTRIBUTE).__iter__()
Expand Down
20 changes: 10 additions & 10 deletions praw/models/listing/listing.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,14 +10,14 @@ class Listing(PRAWBase):
AFTER_PARAM = "after"
CHILD_ATTRIBUTE = "children"

def __len__(self) -> int:
"""Return the number of items in the Listing."""
return len(getattr(self, self.CHILD_ATTRIBUTE))

def __getitem__(self, index: int) -> Any:
"""Return the item at position index in the list."""
return getattr(self, self.CHILD_ATTRIBUTE)[index]

def __len__(self) -> int:
"""Return the number of items in the Listing."""
return len(getattr(self, self.CHILD_ATTRIBUTE))

def __setattr__(self, attribute: str, value: Any):
"""Objectify the ``CHILD_ATTRIBUTE`` attribute."""
if attribute == self.CHILD_ATTRIBUTE:
Expand All @@ -36,12 +36,6 @@ def after(self) -> Optional[Any]:
return getattr(self, "next", None)


class ModeratorListing(Listing):
"""Special Listing for handling moderator lists."""

CHILD_ATTRIBUTE = "moderators"


class ModNoteListing(Listing):
"""Special Listing for handling :class:`.ModNote` lists."""

Expand All @@ -56,6 +50,12 @@ def after(self) -> Optional[Any]:
return getattr(self, "end_cursor", None)


class ModeratorListing(Listing):
"""Special Listing for handling moderator lists."""

CHILD_ATTRIBUTE = "moderators"


class ModmailConversationsListing(Listing):
"""Special Listing for handling :class:`.ModmailConversation` lists."""

Expand Down

0 comments on commit fd5741b

Please sign in to comment.