I am writing a class that stores credentials. The credential can have a password_getter attribute which stores a lambda that will get the password on-demand. This getter needs access to self.username in order to function. How can this be accomplished? Consider the following setup:
class Credential:
"""Defines one username and password combination, and how to get them."""
def __init__(self, username: str, password_getter: callable):
self.username = username
self._password_getter = password_getter
@property
def password(self) -> str:
self.password = self._password_getter()
return self.password
Then we define a new credential:
cred = Credential(
username="test",
password_getter=lambda self: self.username+"_pass",
)
assert cred.password == "test_pass"
The above is non-functional due to self not existing during definition, but it suggests what I'm trying to do: Access the current value of cred.username from inside the lambda.
For some context as to why this is happening; the function in production actually goes out to a password vault api and requests the password for the given username.
selfwhen calling the getter, or you uselambda: cred.username + '_pass'.python username="test" cred = Credential( username="username", password_getter=lambda : username+"_pass", )usernamelater. Thegetterneeds to be able to use the currentusernamein its response.Credentialif it needs access to state stored on the instance? You can still call out to any 3rd party fn you need.Credentialjust defines a framework for storing and retrieving usernames and passwords. The actualgettercode varies significantly between credentials, ranging from checking environment variables to querying remote APIs. I could subclassCredentialfor each cred, but that just seemed bulky if I could use lambdas.