Search code examples
pythonreplacepydantic

Hide variable (e.g. 'password') from print and call of pydantic data model


I am using pydantic for some user/password data model. When the model is printed, I want to replace the value of password with something else (*** for example) to prevent that the password is e.g. written into log-files or the console accidentally.

from pydantic import BaseModel

class myUserClass(BaseModel):
    User = 'foo'
    Password = 'bar'

    def __str__(self):
        return "Hidden parameters."

U = myUserClass()

print(U)
# > Hidden parameters. # Should be User='foo', Password='***' or similar

U # This will still show my password.
#> myUserClass(User='foo', Password='bar')

How can I access the string that is normally printed and replace only 'bar' with '***', but keeping all parameters?

How can I also do that when just calling U? This may not be equally important as for logging and console output usually print is called.


Solution

  • Pydantic provides SecretStr data type. Which is replaced by *** when converted to str (e.g printed) and actual value can be obtained by get_secret_value() method:

    class Foobar(BaseModel):
        password: SecretStr
        empty_password: SecretStr
    
    # Initialize the model.
    f = Foobar(password='1234', empty_password='')
    
    
    # Assert str and repr are correct.
    assert str(f.password) == '**********'
    assert str(f.empty_password) == ''
    
    # Assert retrieval of secret value is correct
    assert f.password.get_secret_value() == '1234'
    assert f.empty_password.get_secret_value() == ''