After some “miscommunications about coding standards”, Nicolas’s company decided that they should have one of their internal developers do code reviews on anything that came from their external, third-party developers. Nicolas drew the short straw on the most recent project.
The specific problem in play is that they had config-data, structured as nested dictionaries. You know the kind of data-structure- something like:
{
database: {
connString: "someDb:abc:123",
pageSize: 50
},
api: {
url: "https://foo/data",
defaultHeaders: {
"X-Api-Key": "d0908ad1-3e28-419f-ab05-0c74eae1ca37"
}
}
}
In their specific configuration, keys could be nested to any arbitrary depth. Someone wanted a helper method, that, given an array of keys: ["api", "defaultHeaders", "X-Api-Key"]
, could return the value associated with the key.
You might be thinking of some iterative or recursive approach for walking the tree, but a smart Python programmer knows that unrolling a loop boosts performance… right? Is that how it works? Well, no matter:
def getObjectValue( listObj):
""" returns the value of the required object by construction the object from the list of string values """
x = len(listObj)
if x == 1:
return config_data_list[listObj[0]]
if x == 2:
return config_data_list[listObj[0]][listObj[1]]
if x == 3:
return config_data_list[listObj[0]][listObj[1]][listObj[2]]
if x == 4:
return config_data_list[listObj[0]][listObj[1]][listObj[2]][listObj[3]]
if x == 5:
return config_data_list[listObj[0]][listObj[1]][listObj[2]][listObj[3]][listObj[4]]
if x == 6:
return config_data_list[listObj[0]][listObj[1]][listObj[2]][listObj[3]][listObj[4]][listObj[5]]
if x == 7:
return config_data_list[listObj[0]][listObj[1]][listObj[2]][listObj[3]][listObj[4]][listObj[5]][listObj[6]]
Good thing their config file doesn’t have 8 nested levels of configuration data. Then again, why does someone’s config data have 7 nested levels?