-2

Using a dataclass really cleans up the class when trying to get many arguments into member variables, but I'm wondering if there's an elegant way to get arguments into the class, especially like this:

@dataclass
class Ship:
    width: int
    height: int
    ...


def get_ships():
    ...

def get_data(ship):
    ...

def main():
    ships = []

    for ship in get_ships():
        ship_data: List[int] = get_data(ship)
        ship = Ship(ship_data[0], ship_data[1], ship_data[2], ship_data[3],
                    ship_data[4], ship_data[5], ship_data[6], ship_data[7],
                    ship_data[8], ship_data[9], ship_data[10], ship_data[11],
                    ship_data[12], ship_data[13], ship_data[14], ship_data[15],
                    ship_data[16], ship_data[17], ship_data[18], ship_data[19],
                    ship_data[20], ship_data[21], ship_data[22], ship_data[23],
                    ship_data[24], ship_data[25], ship_data[26], ship_data[27],
                    ship_data[28], ship_data[29], ship_data[30], ship_data[31])

        ships.append(ship)

It would be great pass the ship_data list itself as an argument into the class, but that would require processing on the class side to get the list elements into the member variables, which ruins the elegance of dataclasses. So I'm wondering if there's a better way to get these arguments in, because this code screams that it could be shorter.

jl8n
  • 53
  • 6

1 Answers1

1

Use asterisks -

for ship in get_ships():
        ship_data: List[int] = get_data(ship)
        ship = Ship(*ship_data)

If you want only 32 elements and not more from ship_data, then use list slicing -

ship = Ship(*ship_data[:32])

Only gets 31 elements, and ignores anything more than that.

PCM
  • 2,881
  • 2
  • 8
  • 30
  • I absolutely hate things like this, because it's so fantastic but I have no clue how I could've found it by searching. Appreciate it. – jl8n Sep 15 '21 at 04:54
  • If you search for `python list Unpacking` you would have got it. But you would not know that you wanted this :) – PCM Sep 15 '21 at 04:55