Skip to content
Advertisement

Appending a list based on some condition [closed]

Background

I have a function called process_player_info where i use a list called fieldnames to do some further processing. In particular the list fieldnames varies depending on if some file called list.txt exists.

So the logic is simple if the file called list.txt exists in the delivery Path then i add one more string to the fieldnames.

Below is my Logic but i am how can i make this more pythonic?

I also thought about just having two fieldnames lists and choose one depending on if list.txt exists but thought that might not be pythonic.

My Code

def _get_fieldnames(delivery: Path) -> List[str]:
    fieldnames = [
        "pay_rate",
        "player_age",
        "cluster_file",
        "player_id",
    ]
    if (delivery / "list.txt").exists():
        fieldnames.insert(3, "coach_file_name")
    return fieldnames

def process_player_info(delivery: Path) -> List[str]:
       fieldnames = _get_fieldnames()
       # process info
       return []

Advertisement

Answer

Honestly, your original code is basically fine, except the magic index “3”. But, the function is short enough, for now, that it shouldn’t be hard to adjust or change that in the future.

One possible improvement would be to make the position of the extra field a bit more explicit:

fieldnames = [
    "pay_rate",
    "player_age",
    "cluster_file",
    *(["coach_file_name"] if (delivery / "list.txt").exists() else []),
    "player_id",
]

Personally, this looks a bit ugly because of the ternary. Another approach:

extrafields = []
if (delivery / "list.txt").exists():
    extrafields.append("coach_file_name")
fieldnames = [
    "pay_rate",
    "player_age",
    "cluster_file",
    *extrafields,
    "player_id",
]

Maybe this is a bit more explicit than an insert call with a magic index.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement