I'm trying to figure out a way to best handle multiple path files that are very similar to one another. While my code works, I feel like it's cumbersome, harder to maintain and difficult to scale without alot of manual work (For example suppose I need to keep adding more and more paths that are just slightly different.
Ideally, I would like to apply the DRY principle as much as possible and not have if-else statements all over the place if there is a better solution.
I thought that using dictionaries or a class might be some improvement but it felt cumbersome to also store paths in a dictionary. I'm not as experienced with classes so I couldn't get it to work without a ton of workarounds (I don't think I was constructing the class properly)
Code
def save_df(df, banner, year, month):
base_path = r'common\path\{0}\for\all\banners\{1}'.format(banner.upper(), year)
if banner in ('a', 'b'):
if month < 10:
# The zero is so I can have the file month in '01, 02, etc.' format
default_path = os.path.join(base_path, '{0}-0{1}_TEST'.format(year, month))
else:
default_path = os.path.join(base_path, '{0}-{1}_TEST'.format(year, month))
else:
if month < 10:
default_path = os.path.join(base_path, '{0}_{1}-0{2}_TEST'.format(banner.upper(), year, month))
else:
default_path = os.path.join(base_path, '{0}_{1}-{2}_TEST'.format(banner.upper(), year, month))
saved_output = [df, default_path]
return saved_output
No problems for the path, works as intended. I believe the code can be improved by refactoring, however, I'm not sure the best way to go about handling conditions that are very similar without repetition.
Aucun commentaire:
Enregistrer un commentaire