Trying to dynamically change part of a function call

Viewed 18

I might be (probably am) using the wrong terminology for some of this, but here's what I'm trying to do.

This is the current code:

with open('matchup' + MatchupStr_Test + '_' + HomeAway[MatchupNum_Test] + 'team_name_NewTest.txt', 'w') as f:
            f.write(str(box_scores[MatchupNum[MatchupNum_Test]].home_team.team_name))

I am attempting to take the word home from the second line (.home_team.team_name) and having it dynamically change so the word home would change depending on an array.

Here's what I thought would work, but doesn't.

with open('matchup' + MatchupStr_Test + '_' + HomeAway[MatchupNum_Test] + 'team_name_NewTest.txt', 'w') as f:
            f.write(str(box_scores[MatchupNum[MatchupNum_Test]].[HomeAway[MatchupNum_Test]]_team.team_name))

Absolute beginner here, so sorry if I'm wording this in a confusing way. Just trying to have some fun on a Raspbi I wasn't currently using, so it doesn't have to be perfect.

1 Answers

There is a function called getattr, which should work for this. The way getattr works is that it dynamically retrieves a property of an object using the name of the property.

For example:

team_name = HomeAway[MatchupNum_Test]

with open(f'matchup{MatchupStr_Test}_{team_name}team_name_NewTest.txt', 'w') as f:
  opposing_team = getattr(box_scores[MatchupNum[MatchupNum_Test]], f'{team_name}_team')
  f.write(str(opposing_team.team_name))

In the above, we dynamically retrieve the attribute f'{team_name}_team' from the object box_scores[MatchupNum[MatchupNum_Test]].

So if team_name was "home" for example, then getattr(box_scores[MatchupNum[MatchupNum_Test]], f'{team_name}_team') will be equivalent to box_scores[MatchupNum[MatchupNum_Test]].home_team


The f in front of the strings has nothing to do with the f representing the file. They are called f-strings and are a much nicer way of combining strings, than using +.

Related