cygnusoid
cygnusoid

Reputation: 21

How to handle an increasing number of operations in a python class

I'm trying to improve my code design skills but not sure what to do. Currently I have a class that needs to set certain keys on init and it looks something like this:

class A:
  def __init__(self):
    try:
      self.key1 = some_key_finder("key1")
      self.key2 = some_key_finder("key2")
      self.key3 = some_key_finder("key3")
    except KeyError as err:
      raise SecretNotFoundError(f"...{err}")

Initially it only set one key but as the reqs changed I had to set two more keys. My question is: how to make the above code more scalable and handle an (hypothetically) increasing number of keys?

Upvotes: 1

Views: 40

Answers (1)

TDk
TDk

Reputation: 1059

You could store your keys and their results in a class attribute :

class A:
    def __init__(self, keys=None) -> None:
        self.keys = dict()
        if keys:
            for key in keys:
                self.enroll(key)
    
    def enroll(self, key: str) -> None:
        try:
            self.keys[key] = some_key_finder(key)
        except KeyError as err:
          raise SecretNotFoundError(f"...{err}")
    
    def lookup(self, key: str) -> str:
        return self.keys[key]

Later, you can enroll a new key like so :

a = A(keys=['key1', 'key2', 'key3'])
a.enroll(key='key4')

Upvotes: 1

Related Questions