Home > Software design >  Best way to assign lots of self variables to elements in a list?
Best way to assign lots of self variables to elements in a list?

Time:10-20

I am essentially trying to assign a distinct variable to each element from a list. I attached some code below to better explain what I mean:

class Skill:
    def __init__(self, name):
        skill_detail = SKILLS_LIST[name].values()
        
        self.one = skill_detail[0]
        self.two = skill_detail[1]
        self.three = skill_detail[2]
        self.four = skill_detail[3]
        self.five = skill_detail[4]
        self.six = skill_detail[5]
        self.seven = skill_detail[6]
        self.eight = skill_detail[7]
        self.nine = skill_detail[8]

I have thought switching to slicing but what would the best way to do this? Any help would be appreciated, thank you!

Context:

The variables are basically attributes of a move in an RPG game. Things like power, accuracy, priority, type, energy cost, etc. Which is why I feel all the separate attributes are necessary as self variables, but not yet sure.

Also, I know that global variables/constants are bad but 'SKILLS_LIST' is a massive dictionary pulled from a json file that will never be mutated in the code.

CodePudding user response:

What you're doing isn't necessarily bad practice I'd say, especially if you have only a few attributes.

But you mention loading data from a JSON file into a dictionary, and dictionaries are already a programmatic way to create a variable number of variables. So why not just use a dictionary. and whenever you need to modify or read a certain attribute, you can just do skills["power"], skills["cost"], etc. This also would probably be much more scalable as your project develops in size and complexity.

Of course, if you have no control of how said JSON file is formatted, that would complicate things. In such a case I don't see anything wrong with loading the attributes manually.

CodePudding user response:

I suppose it would make sense to use a model class like a named tuple for this, if you wanted to. One benefit of this is that it's essentially just a tuple, so it's inherently JSON serializable in case you need to convert it back to a list as below.

import json
from typing import NamedTuple


class MyTup(NamedTuple):
    one: str
    two: str
    three: str


c = MyTup(*["hello", "world", "!"])
print(c)
# MyTup(one='hello', two='world', three='!')
print(c.two)
# world
print(json.dumps(c))
# ["hello", "world", "!"]
  • Related