Python Organising a Two-File Program
A two-file program is a program split across two files. Each file owns one job, so each file stays short.
The data file
scores_data.py holds only the scores. Nothing else lives in that file.
with open("scores_data.py", "w") as f:
f.write("scores = [88, 95, 71, 92]\n")
import scores_data
print(scores_data.scores)
print(len(scores_data.scores))The logic file
scores_logic.py imports the data file. Its average function reads the scores from there.
with open("scores_data.py", "w") as f:
f.write("scores = [88, 95, 71, 92]\n")
with open("scores_logic.py", "w") as f:
f.write("import scores_data\n\ndef average():\n total = 0\n for s in scores_data.scores:\n total = total + s\n return total / len(scores_data.scores)\n")
import scores_logic
print(scores_logic.average())The main file calls both
The main program is short. It imports the logic file and prints the best score.
with open("scores_data.py", "w") as f:
f.write("scores = [88, 95, 71, 92]\n")
with open("scores_logic.py", "w") as f:
f.write("import scores_data\n\ndef best():\n return max(scores_data.scores)\n")
import scores_logic
print("Best score:", scores_logic.best())Example
with open("team_data.py", "w") as f:
f.write("players = [{'name': 'Ada', 'score': 90}, {'name': 'Bob', 'score': 95}, {'name': 'Cy', 'score': 70}]\n")
with open("team_logic.py", "w") as f:
f.write("import team_data\n\ndef average():\n total = 0\n for p in team_data.players:\n total = total + p['score']\n return total / len(team_data.players)\n\ndef top():\n best = team_data.players[0]\n for p in team_data.players:\n if p['score'] > best['score']:\n best = p\n return best['name']\n")
import team_logic
print("Average:", team_logic.average())
print("Top player:", team_logic.top())Key points
- Owner: the one file that holds a piece of the program
- Put the data in one file and the logic in the other
- The logic file imports the data file, never the other way round
- Put shared values in the data file, so both files read the same numbers
- Keep the main program short. It only calls the pieces together.
- One file doing two jobs is the sign to split it
In this example, team_data.py holds the players and nothing else. team_logic.py imports that file and holds two functions. average adds the three scores and divides by three. top walks the players and keeps the one with the highest score. The main program prints both answers. The data, the logic, and the main program each own one job.
Note
Splitting too early is also a cost. One short file needs no split.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Python Playground
Exercise
In a two-file program, where does the data live?