Search code examples
pythonpropertiesconstants

Python constant uuid token in class (property does not work)


I need a class that remembers its constant token (uuid). When I use the property decorator as described here, the property will prevent the uuid function from changing, but not the value:

from uuid import uuid4

class Tokenizer:
    @property
    def token(self):
        return uuid4().hex

t = Tokenizer()

print(t.token)
print(t.token)

This prints diffrent tokens, so how can I achieve the constant token so the output will be the same, without passing token to the class as argument?

Edit: t.__token can by changed but does not affect t.token. Do you know why?

from uuid import uuid4

class Tokenizer:
    def __init__(self):
        self.__token = uuid4().hex
    
    @property
    def token(self):
        return self.__token

t = Tokenizer()

print(t.token)
print(t.token)

Solution

  • What is basically done here is I am creating a token if it does not exist and if the instance of class has already set the token, then we will be returning the existing token.

    The __token variable in the updated code is not modifiable because it is a class-level variable, and it is defined with double underscores as __token. This makes it a private variable that cannot be accessed or modified directly from outside the class.

    from uuid import uuid4
    
    class Tokenizer:
        def __init__(self):
            self.__token = uuid4().hex
        
        @property
        def token(self):
            return self.__token
    
    t = Tokenizer()
    
    print(t.token)
    print(t.token)