1

I am creating a wrapper Python API for twitter,

For example:

search_tweets(**kwargs)

This API returns back a Tweet object. Tweet class looks something like:

class Tweet:
    def __init__(self, tweet, favorites, impressions, engagements, **kwargs):
        """ Create a new Tweet Object with field values """
        self.impressions = impressions
        self.favorites = favorites
        self.tweet = tweet
        self.engagements = engagements
        vars(self).update(kwargs)


    def retweet():
       """ Retweet this tweet """

Tweet object will be exposed to users because Tweet object will be returned by search_tweets API and users can call methods like retweet on this object, but I do not want users to explicitly create this object.

How can I denote that Tweet object should not be created by users, it should only be operated upon?

1
  • def __init__(self, tweet, favorites, impressions, engagements, do_i_know_what_im_doing, **kwargs): if do_i_know_what_im_doing !='yes_i_do': raise RuntimeError Commented Nov 2, 2018 at 9:58

2 Answers 2

1

You can make Tweet class local to the function, for example:

def search_tweets(**kwargs):
    class Tweet:
        ...

So, the user can call retweet() and other methods on objects returned from search_tweets() function, but cannot easily create Tweet objects by hand due to the lack of human-readable name. But the drawback of this approach is that it will be equally difficult to create Tweets from other API functions.

Sign up to request clarification or add additional context in comments.

1 Comment

Correct, with this approach it will be difficult to create Tweets from other API functions. I am sure if this is a very generic use-case and people would have thought multiple solutions for this.
1

You could use the single underscore convention (PEP documentation).

_single_leading_underscore: weak "internal use" indicator. E.g. from M import * does not import objects whose name starts with an underscore.

There is nothing "private" in Python, without having to jump through a bunch of hoops. The best thing you can do is follow convention and comment the class well.

1 Comment

_single_leading_underscore, I think this will give a wrong impression that the class in private? But users are still using methods on this class for example retweet()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.