0

I am writing a bit of Python code to use a list to store order data. Is there any way to avoid having to repeatedly use the same arguments?

import datetime, pickle

class Order:

    def __init__(self, order_number_legacy, platform, value, user_id):
        self.order_number_legacy = order_number_legacy
        self.platform = platform
        self.value = value
        self.user_id = user_id

    def match(self, order_number_legacy):
        return filter in self.order_number_legacy

    def print(self):
        return f"{self.order_number_legacy}, {self.platform}, {self.value}, {self.user_id}\n"    

class Orders:

    def __init__(self):
        self.orders = []

    def newOrder(self, order_number_legacy, platform, value, user_id):
        self.orders.append(Order(order_number_legacy, platform, value, user_id))

    def save(self):
        with open("orders.data", "wb") as fh:
            pickle.dump(self.orders, fh)

    def load(self):
        with open("orders.data", "rb") as fh:
            self.orders = pickle.load(fh)

    def print(self):
        text = ""
        for order in self.orders:
            text += order.print()
        return text

You can see that I have several instances of the arguments "order_number_legacy, platform, value, user_id". Once I have added all of the Order class variables, the code will have lots more arguments repeated. I would have thought Python would have a way to "tidy" this up...

1 Answers1

0

You can use a dataclass for Order. It'll automatically take care of the __init__ function:

from dataclasses import dataclass

@dataclass
class Order:
    order_number_legacy: int
    platform: str
    # ...
Karoo
  • 542
  • 6
  • 19
  • Great, does the job perfectly. Is there something similar I can do with the newOrder function? ` def newOrder(self, order_number_legacy, platform, value, user_id): self.orders.append(Order(order_number_legacy, platform, value, user_id))` –  Feb 17 '21 at 16:40
  • You can either use `locals()` and ignore `self`, as in https://stackoverflow.com/a/53997999/432733, or use `kwargs` as in https://stackoverflow.com/a/42507706/432733. – Karoo Feb 18 '21 at 08:15
  • I went with the `*args` option. This is great as it saves me adjusting lots of code when adding a new variable to the class. –  Feb 18 '21 at 09:03
  • How would I declare an empty list in the Order class that is not included in the arguments? `@dataclass class Order: order_number_legacy: int platform: str log: List[Log]` –  Feb 19 '21 at 08:33
  • This appears to work:`order_number_legacy: str platform: str value: str user_id: str name: str logs: List[Log] = Logs()` –  Feb 19 '21 at 08:59
  • Okay, I have sussed it now. The @dataclass works perfectly. If needing to add any other variables not referred to in the arguments use `def __post_init__(self):` and add the variables as they normally would be entered under `def __init__(self):` –  Feb 19 '21 at 13:47