Mohamed Samir
Mohamed Samir

Reputation: 399

instantiate class in python as a callable object

I found this block of code which instantiates a class with an object but we used it as a callable even without defining a __call__ method. Here is the code of the class in Django source code on Github code of the class

You can see the instantiation at the bottom of page, too and here we used it used it by inheriting from it:

class TokenGenerator(PasswordResetTokenGenerator):
def _make_hash_vlaue(self, user, timestamp):
    return (str(user.pk)+str(timestamp)+str(user.is_active))

account_activation_token = TokenGenerator()

Here is the call of the instantiated instance in the token key of the dictionary:

message = render_to_string('acc_activate_email.html',
                                    {'user': new_user, 
                                     'domain': current_site.domain,
                                     'uid': urlsafe_base64_encode(force_bytes(new_user.pk),
                                     'token': account_activation_token(new_user))})

You can take a look at the original code here original code where we used the object

Upvotes: 0

Views: 227

Answers (2)

C.Nivs
C.Nivs

Reputation: 13106

You can do this with a __call__ method on the class:

class TokenGenerator(PasswordResetTokenGenerator):
    def make_token(self, user, timestamp):
        return (str(user.pk)+str(timestamp)+str(user.is_active))

    def __call__(self, user, password):
        return self.make_token(user, timestamp)


t = TokenGenerator()
t(someuser, sometimestamp)
# some hash

However, I'm not really convinced you need to, as you have a class where the make_token method doesn't reference anything in the class at all. A function would do just as much here:

generate_token(user, timestamp):
    return (str(user.pk)+str(timestamp)+str(user.is_active))

generate_token(someuser, sometimestamp)
# some hash

Realistically, the way they use it in the docs is by calling that instance method from the instance like:

t = TokenGenerator()

t._make_hash_vlaue(someuser, sometimestamp)

Upvotes: 0

mcabrams
mcabrams

Reputation: 686

Perhaps your question was made prior to the aforementioned code from the article, but the actual code now is

'token':account_activation_token.make_token(user),

which would be a proper call of the make_token method. With the code you had pasted above, calling account_activation_token(user) would raise a `TypeError: 'TokenGenerator' object is not callable error.

Upvotes: 1

Related Questions