Refactor the following code to be cleaner with no redundant code or logic.
CODE:
for court_type in court_types:
courts = get_all_courts(ASPXAUTH, court_type)["d"][0]["children"]
print(courts)
for court in courts:
print(court)
subcourts = get_subcourts(ASPXAUTH, court_type, str(court["key"]).split("$")[0])["d"][0]["children"]
print('subcourts',subcourts)
code
Assistant
if subcourts[0]['level'] == 'Year':
years = [int(year['key'].split("$")[0]) for year in subcourts]
print(years)
for year in years:
print('years',year)
moth = 12
current_day = 31
# if year == 2024:
# moth = datetime.datetime.now().month
# current_day = datetime.datetime.now().day
print('m,d',moth,current_day)
progress_bar = tqdm(total=(31 * 12),
desc=f'Processing for the court type {court_type} and the court name {str(court["key"]).split("$")[0]} in year {year}')
last_completed_day = get_last_completed_day(court_type, str(court["key"]).split("$")[0], year)
for month in range(1, moth+1):
for day in range(1, current_day+1):
if last_completed_day:
if day > last_completed_day[1] and month > last_completed_day[0]:
semaphore.acquire() # acquire the semaphore before starting a new thread
thread = threading.Thread(target=process_day_threaded_safe,
args=(conn,court_type, court, None, year, month, day))
thread.start()
threads.append(thread)
progress_bar.update(1)
else:
progress_bar.update(1)
else:
semaphore.acquire() # acquire the semaphore before starting a new thread
thread = threading.Thread(target=process_day_threaded_safe,
args=(conn,court_type, court, None, year, month, day))
thread.start()
threads.append(thread)
progress_bar.update(1)
progress_bar.close()
elif subcourts[0]['level'] == 'YearRange':
for yearrange in subcourts:
min_year = int(str(yearrange['key'].split("$")[0]).split(" - ")[0])
max_year = int(str(yearrange['key'].split("$")[0]).split(" - ")[1])
print(f"min year {min_year} \n max year {max_year}")
# progress_bar = tqdm(total=(((max_year + 1) - min_year) * 31 * 12),
# desc=f'Processing for the court type {court_type} and the court name {str(court["key"]).split("$")[0]} in year range {str(yearrange["key"].split("$")[0])}')
min_year = 2024
max_year = 2025
for year in range(min_year, max_year + 1):
# current_day = 31
# if year == 2024:
# moth = datetime.datetime.now().month
# current_day = datetime.datetime.now().day
last_completed_day = get_last_completed_day(court_type, str(court["key"]).split("$")[0], year)
print('yearrange',year)
for month in range(1, 13):
print('yearrange month',month)
current_day = calendar.monthrange(year, month)[1]
for day in range(1, current_day):
print('yearrange day',day)
if last_completed_day:
print("This is working")
current_date: datetime.date = datetime.date(year, month, day)
today: datetime.date = datetime.date.today()
print('yearrange greater than today',current_date > today)
if current_date > today:
break
last_completed_date = datetime.date(year, last_completed_day[0], last_completed_day[1])
# Convert the current day to a datetime object for comparison
print('last',current_date,last_completed_date)
if current_date > last_completed_date:
print('lprcessing',(day,month))
semaphore.acquire() # acquire the semaphore before starting a new thread
thread = threading.Thread(target=process_day_threaded_safe,
args=(conn,court_type, court, None, year, month, day))
thread.start()
threads.append(thread)
# progress_bar.update(1)
else:
print('not prcessing',(day,month))
# progress_bar.update(1)
else:
semaphore.acquire() # acquire the semaphore before starting a new thread
thread = threading.Thread(target=process_day_threaded_safe,
args=(conn,court_type, court, None, year, month, day))
thread.start()
threads.append(thread)
# progress_bar.update(1)
# progress_bar.close()
else:
for sub in subcourts:
subcourt = str(sub['key'].split("$")[0])
years = \
get_year_range_for_subcourt(ASPXAUTH, str(court["key"]).split("$")[0], subcourt, court_type)["d"][
0]["children"]
if years[0]['level'] == 'Year':
years = [int(year['key'].split("$")[0]) for year in years]
for year in years:
moth = 12
current_day = 31
print(year)
# if year == 2024:
# moth = datetime.datetime.now().month
# current_day = datetime.datetime.now().day
# print(moth,current_day)
progress_bar = tqdm(total=(31 * 12),
desc=f'Processing for the court type {court_type} and the court name {str(court["key"]).split("$")[0]} for the sub court {subcourt} in year {year}')
last_completed_day = get_last_completed_day(court_type, subcourt,year)
for month in range(1, moth+1):
for day in range(1, current_day+1):
if last_completed_day:
if day > last_completed_day[1] and month > last_completed_day[0]:
semaphore.acquire() # acquire the semaphore before starting a new thread
thread = threading.Thread(target=process_day_threaded_safe,
args=(conn,court_type, court, subcourt, year, month, day))
thread.start()
threads.append(thread)
progress_bar.update(1)
else:
progress_bar.update(1)
else:
semaphore.acquire() # acquire the semaphore before starting a new thread
thread = threading.Thread(target=process_day_threaded_safe,
args=(conn,court_type, court, subcourt, year, month, day))
thread.start()
threads.append(thread)
progress_bar.update(1)
progress_bar.close()
elif years[0]['level'] == 'YearRange':
for yearrange in years:
min_year = int(str(yearrange['key'].split("$")[0]).split(" - ")[0])
max_year = int(str(yearrange['key'].split("$")[0]).split(" - ")[1])
progress_bar = tqdm(total=(((max_year + 1) - min_year) * 31 * 12),
desc=f'Processing for the court type {court_type} and the court name {str(court["key"]).split("$")[0]} for the sub court {subcourt} in year range {str(yearrange["key"].split("$")[0])}')
for year in range(min_year, max_year + 1):
moth = 12
current_day = 31
# if year == 2024:
# moth = datetime.datetime.now().month
# current_day = datetime.datetime.now().day
last_completed_day = get_last_completed_day(court_type, subcourt, year)
for month in range(1, moth+1):
for day in range(1, current_day + 1):
if last_completed_day:
if day > last_completed_day[1] and month > last_completed_day[0]:
semaphore.acquire() # acquire the semaphore before starting a new thread
thread = threading.Thread(target=process_day_threaded_safe,args=(conn,court_type, court, subcourt, year, month, day))
thread.start()
threads.append(thread)
progress_bar.update(1)
else:
progress_bar.update(1)
else:
semaphore.acquire() # acquire the semaphore before starting a new thread
thread = threading.Thread(target=process_day_threaded_safe,args=(conn,court_type, court, subcourt, year, month, day))
thread.start()
threads.append(thread)
progress_bar.update(1)
progress_bar.close()
Certainly! The provided code involves nested loops and conditional branches that handle different levels of court data processing (Year, YearRange, and others). There is significant repetition, especially in handling threading, semaphore acquisition, and progress bar updates. To make the code cleaner and more maintainable, we can:
Abstract Repetitive Logic: Create helper functions for repeated tasks like processing days, handling threading, and updating progress bars.
Modularize Processing Steps: Separate the logic for handling Year, YearRange, and other subcourt levels into distinct functions.
Eliminate Redundant Code: Remove commented-out code and unify similar code paths.
Below is the refactored version implementing these improvements:
python
import threading
import datetime
import calendar
from tqdm import tqdm
# Assuming the following variables and functions are defined elsewhere:
# ASPXAUTH, court_types, conn, semaphore, threads,
# get_all_courts, get_subcourts, get_year_range_for_subcourt,
# get_last_completed_day, process_day_threaded_safe
def extract_key(key):
"""Extracts the first part of the key before the '$' delimiter."""
return str(key).split("$")[0]
def acquire_thread(semaphore, target, args, threads):
"""Acquires a semaphore and starts a new thread."""
semaphore.acquire()
thread = threading.Thread(target=target, args=args)
thread.start()
threads.append(thread)
def process_day(conn, court_type, court, subcourt, year, month, day, progress_bar):
"""Processes a single day with threading and updates the progress bar."""
acquire_thread(
semaphore,
process_day_threaded_safe,
(conn, court_type, court, subcourt, year, month, day),
threads
)
progress_bar.update(1)
def handle_years(conn, court_type, court, subcourt, years, progress_desc):
"""Handles processing for a list of years, updating progress."""
total_days = sum(calendar.monthrange(year, month)[1] for year in years for month in range(1, 13))
with tqdm(total=total_days, desc=progress_desc) as progress_bar:
for year in years:
last_completed = get_last_completed_day(court_type, subcourt, year)
for month in range(1, 13):
current_day = calendar.monthrange(year, month)[1]
for day in range(1, current_day + 1):
current_date = datetime.date(year, month, day)
today = datetime.date.today()
if current_date > today:
progress_bar.update(current_day - day + 1)
break
if last_completed:
last_month, last_day = last_completed
last_completed_date = datetime.date(year, last_month, last_day)
if current_date > last_completed_date:
process_day(conn, court_type, court, subcourt, year, month, day, progress_bar)
else:
progress_bar.update(1)
else:
process_day(conn, court_type, court, subcourt, year, month, day, progress_bar)
def handle_year_ranges(conn, court_type, court, subcourt, year_ranges, progress_desc):
"""Handles processing for a list of year ranges, updating progress."""
all_years = []
for yr in year_ranges:
min_year, max_year = map(int, yr['key'].split("$")[0].split(" - "))
all_years.extend(range(min_year, max_year + 1))
total_days = sum(calendar.monthrange(year, month)[1] for year in all_years for month in range(1, 13))
with tqdm(total=total_days, desc=progress_desc) as progress_bar:
for year in all_years:
last_completed = get_last_completed_day(court_type, subcourt, year)
for month in range(1, 13):
current_day = calendar.monthrange(year, month)[1]
for day in range(1, current_day + 1):
current_date = datetime.date(year, month, day)
today = datetime.date.today()
if current_date > today:
progress_bar.update(current_day - day + 1)
break
if last_completed:
last_month, last_day = last_completed
last_completed_date = datetime.date(year, last_month, last_day)
if current_date > last_completed_date:
process_day(conn, court_type, court, subcourt, year, month, day, progress_bar)
else:
progress_bar.update(1)
else:
process_day(conn, court_type, court, subcourt, year, month, day, progress_bar)
def process_subcourts(conn, court_type, court, subcourts):
"""Processes all subcourts based on their level."""
for sub in subcourts:
subcourt_key = extract_key(sub['key'])
years_data = get_year_range_for_subcourt(ASPXAUTH, extract_key(court["key"]), subcourt_key, court_type)["d"][0]["children"]
if not years_data:
continue # Skip if no years data available
level = years_data[0]['level']
if level == 'Year':
years = [int(extract_key(year['key'])) for year in years_data]
desc = f'Processing {court_type} - {extract_key(court["key"])} - {subcourt_key} - Years'
handle_years(conn, court_type, court, subcourt_key, years, desc)
elif level == 'YearRange':
desc = f'Processing {court_type} - {extract_key(court["key"])} - {subcourt_key} - YearRanges'
handle_year_ranges(conn, court_type, court, subcourt_key, years_data, desc)
else:
print(f"Unknown level '{level}' for subcourt '{subcourt_key}'.")
def main():
"""Main processing function."""
for court_type in court_types:
courts = get_all_courts(ASPXAUTH, court_type)["d"][0]["children"]
print(f"Courts for type '{court_type}': {courts}")
for court in courts:
print(f"Processing court: {court}")
subcourts = get_subcourts(ASPXAUTH, court_type, extract_key(court["key"]))["d"][0]["children"]
print(f"Subcourts: {subcourts}")
if not subcourts:
continue # Skip if no subcourts available
level = subcourts[0]['level']
if level == 'Year':
years = [int(extract_key(subcourt['key'])) for subcourt in subcourts]
desc = f'Processing {court_type} - {extract_key(court["key"])} - Years'
handle_years(conn, court_type, court, None, years, desc)
elif level == 'YearRange':
desc = f'Processing {court_type} - {extract_key(court["key"])} - YearRanges'
handle_year_ranges(conn, court_type, court, None, subcourts, desc)
else:
# Handle nested subcourts with their own year or year range levels
process_subcourts(conn, court_type, court, subcourts)
# Optionally, wait for all threads to complete
for thread in threads:
thread.join()
if __name__ == "__main__":
main()
Refactoring Highlights
Helper Functions:
extract_key: Simplifies the extraction of the key before the $ delimiter.
acquire_thread: Handles semaphore acquisition and thread starting to avoid repetition.
process_day: Consolidates processing a single day, including thread management and progress updating.
handle_years and handle_year_ranges: Manage processing for Year and YearRange levels respectively, each with their own progress bars and threading logic.
Processing Subcourts:
The process_subcourts function handles subcourts that may have their own nested levels (Year or YearRange), making the code modular and easier to manage.
Main Function:
Encapsulates the primary loop logic, making the script execution clearer.
Includes a loop at the end to join all threads, ensuring that the main program waits for all processing to complete.
Progress Bars:
Each major processing step (Years and YearRanges) has its own tqdm progress bar, providing clear and separate progress indicators.
Removed Redundancies:
Eliminated repeated logic for processing Year and YearRange within each branch by abstracting them into helper functions.
Removed commented-out code to enhance readability.
Error Handling:
Added basic checks (e.g., if not subcourts) to prevent potential errors when expected data isn't available.
Included a default case in process_subcourts to notify about unknown levels, aiding in debugging.
Additional Recommendations
Logging: Instead of using print statements, consider using the logging module for better control over log levels and outputs.
Thread Management: Depending on the size of threads, you might want to implement a thread pool or limit the number of concurrent threads to optimize performance and resource usage.
Configuration: Parameters like moth and current_day are now dynamically determined, but if there are special cases (e.g., partially completed current months), ensure they are handled appropriately.
Error Handling in Threads: Implement error handling within process_day_threaded_safe to manage exceptions that may occur during threaded execution.
This refactored code should be more maintainable, easier to understand, and free from redundant logic. Adjust the helper functions as needed based on the specifics of your environment and additional requirements.