Skip to content

create_instructor_answer errors on string cid input #74

@kwshi

Description

@kwshi

per create_instructor_answer's current documentation the post parameter can be either a string (the post's cid) or dictionary (post object with id key).

def create_instructor_answer(self, post, content, revision, anonymous=False):
"""Create an instructor's answer to a post `post`.
It seems like if the post has `<p>` tags, then it's treated as HTML,
but is treated as text otherwise. You'll want to provide `content`
accordingly.
:type post: dict|str|int
:param post: Either the post dict returned by another API method, or
the `cid` field of that post.
:type content: str
:param content: The content of the answer.
:type revision: int
:param revision: The number of revisions the answer has gone through.
The first responder should out 0, the first editor 1, etc.
:type anonymous: bool
:param anonymous: Whether or not to post anonymously.
:rtype: dict
:returns: Dictionary with information about the created answer.
"""

however passing in a string post actually causes an error/crash: that's because

try:
cid = post["id"]
except KeyError:
cid = post

doesn't handle the type cases correctly. trying to index ["id"] in a string raises a TypeError not a KeyError so it doesn't get caught, and the fallback doesn't work. one possible fix is to catch the TypeError, as is done in some other functions, e.g. update_post:

def update_post(self, post, content):
"""Update post content by cid
:type post: dict|str|int
:param post: Either the post dict returned by another API method, or
the `cid` field of that post.
:type subject: str
:param content: The content of the followup.
:rtype: dict
:returns: Dictionary with information about the updated post.
"""
try:
cid = post["id"]
except KeyError:
cid = post
except TypeError:
cid = post

another fix is to just simplify the API and only take in string post ID instead of str|dict|int; after all that is the only part of the post object needed, so it doesn't logically make sense to require the whole object. for most people typing out an additional ["id"] is not all that much added work, and the benefit is that the API is a lot more consistent and well-typed this way.

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions