-2

I would like to find a function that can return a specific object of a specific list in Python. For example if I have a structure like this :

obj_list = [ "A" , "B" , "C" ]

class ex:
   def __init__(self, var1, var2, var3):
      self.var1 = var1
      self.var2 = var2
      self.var3 = var3

def find(key):
    if key == "A"
       return ex(1, 2, 3)
    if key == "B"
       return ex(2,3,4)
    if key == "C"
       return ex(4,5,6)

exists in python a specific function that allows me to do this operation without using an indefinite set of if ? because in my case imagine that I have a list of element lit_obj much longer I would like to avoid writing many ifs and make the code cleaner enclosing everything in a single function. In typescript for example I can use the record function<K,T> to do this operation, is there a specific in python ? thanks for the help

example in TS:

type MainnetPoolKey = "A" | "B" | "C" ;

interface Pool {
  var1: number;
  var2: number;
  var3: number;
}

const MainnetPools: Record<MainnetPoolKey, Pool> = {
  A: {
    var1: 86498781,
    var2: 0
    var3: 686505742,
  },
  B: {
    var1: 686500029,
    var2: 31566704,
    var3: 86508050,
  },
  C: {
    var1: 86500844,
    var2: 312769,
    var3: 509463,
}
}
Simospa
  • 23
  • 4

1 Answers1

1

I don't know how Record function of typescript works, but I can give you what you want.

solution

Just save everything into dictionary and loading it from function does what you want.

presets = {
    "A": {
        "var1": 1,
        "var2": 2,
        "var3": 3
    },
    "B": {
        "var1": 2,
        "var2": 3,
        "var3": 4
    },
    "C": {
        "var1": 4,
        "var2": 5,
        "var3": 6
    }
}

class ex:
    def __init__(self, var1, var2, var3):
        self.var1 = var1
        self.var2 = var2
        self.var3 = var3

def find(key):
    return ex(**presets[key])

a = find("A")
print(a.var1, a.var2, a.var3) # 1 2 3

** in find function means unpacking dictionary into parameters. Looking at What does ** (double star/asterisk) and * (star/asterisk) do for parameters? will help.

minolee
  • 404
  • 2
  • 8