ThinkGeek
ThinkGeek

Reputation: 5127

Preventing users from creating objects of certain classes in Python

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?

Upvotes: 1

Views: 152

Answers (2)

Fred
Fred

Reputation: 583

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.

Upvotes: 1

trolley813
trolley813

Reputation: 932

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.

Upvotes: 1

Related Questions