0

I have a named tuple object defined with 63 different items in it. I use the _make function. I think this approach will work but need 4x63 more rows for the try except statements. There has to be a better way:

AssetRow = collections.namedtuple('AssetRow', [
    "status",
    "computer_name",
    .
    .
    .
    61 more


def create_asset_row(Object):
    try:
        Object.status
    except
        Object.status = ""
    try:
        Object.computer_name
    except
        Object.computer_name= ""
    values = [
        Object.status,
        Object.computer_name,
        .
        .
        .
        61 more
    ]
    row = AssetRow._make(values)

basically I want to make sure the named tuple is set to "" if I don't have a value to put in it.... but I don't want to write 500 lines to do it... I want to write about 67 lines

gunslingor
  • 1,358
  • 12
  • 34

1 Answers1

1

Would something like this work? I'm not too familiar with the namedtuple class.

names = ["status", "computer_name"]
AssetRow = collections.namedtuple('AssetRow', names)


def create_asset_row(Object):
    values = [getattr(Object, name, "") for name in names]
    row = AssetRow._make(values)
bphi
  • 3,115
  • 3
  • 23
  • 36
  • 1
    I would suggest using the default argument of `getattr`: `getattr(Object, name, "")`. if needed replace `""` with a `name` specific default. As this is closer to the OP's code. – Dan D. Dec 07 '17 at 22:18
  • Thank you, I'd had that thought as well, but forgot to put it in – bphi Dec 07 '17 at 22:19