Skip to content

Commit

Permalink
refactor: change methods not using its bound instance to staticmethods
Browse files Browse the repository at this point in the history
The method doesn't use its bound instance. Decorate this method with `@staticmethod` decorator, so that Python does not have to instantiate a bound method for every instance of this class thereby saving memory and computation. Read more about staticmethods [here](https://docs.python.org/3/library/functions.html#staticmethod).
  • Loading branch information
deepsource-autofix[bot] authored Jan 11, 2025
1 parent e3daf0d commit 8a79903
Show file tree
Hide file tree
Showing 15 changed files with 138 additions and 69 deletions.
6 changes: 4 additions & 2 deletions Cogs/ampa.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,8 @@ def check(m):
logger.error(f"An error occurred: {e}")
await ctx.send(f"An error occurred: {e}")

def list_files(self, search_path: str = ".") -> list:
@staticmethod
def list_files(search_path: str = ".") -> list:
"""List all file paths in the given directory and its subdirectories, ignoring package and cache files."""
file_paths = []
ignore_patterns = [
Expand Down Expand Up @@ -100,7 +101,8 @@ def list_files(self, search_path: str = ".") -> list:

return file_paths

async def send_file_to_user(self, user: discord.User, file_path: str):
@staticmethod
async def send_file_to_user(user: discord.User, file_path: str):
"""Send a file to the specified user via DM, handling size limitations."""
try:
filename = os.path.basename(file_path)
Expand Down
6 changes: 4 additions & 2 deletions Cogs/anime.py
Original file line number Diff line number Diff line change
Expand Up @@ -299,7 +299,8 @@ async def update_embed(self):

return embed

def get_image_url(self, images):
@staticmethod
def get_image_url(images):
size_order = ["large", "medium", "small"]
for size in size_order:
image_url = images.get("jpg", {}).get(f"{size}_image_url")
Expand Down Expand Up @@ -483,7 +484,8 @@ async def update_embed(self):

return embed

def get_image_url(self, images):
@staticmethod
def get_image_url(images):
size_order = ["large", "medium", "small"]
for size in size_order:
image_url = images.get("jpg", {}).get(f"{size}_image_url")
Expand Down
9 changes: 6 additions & 3 deletions Cogs/help.py
Original file line number Diff line number Diff line change
Expand Up @@ -378,7 +378,8 @@ def _draw_text(self, draw, text_x, text_y):
fill=self.base_font_color,
)

def _download_image(self, url):
@staticmethod
def _download_image(url):
"""Download an image from a URL."""
response = requests.get(url)
response.raise_for_status() # Ensure we notice bad responses
Expand Down Expand Up @@ -512,7 +513,8 @@ def _load_resources(self):

self._resize_character()

def _download_image(self, url):
@staticmethod
def _download_image(url):
"""Download an image from a URL and return it as a PIL Image."""
response = requests.get(url)
response.raise_for_status()
Expand Down Expand Up @@ -652,7 +654,8 @@ def _update_command_mapping(self):
mapping[cog_name][cmd.name] = " "
self._save_command_mapping(mapping)

def format_cog_commands(self, cog_name, cog_commands, command_mapping):
@staticmethod
def format_cog_commands(cog_name, cog_commands, command_mapping):
embed = discord.Embed(
title=f"Commands for {cog_name}", color=primary_color_value
)
Expand Down
3 changes: 2 additions & 1 deletion Cogs/information.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,8 @@ async def about(self, ctx, id: Union[discord.Member, int, str] = None):
embed = await self.get_information_embed(id, self.bot)
await ctx.reply(embed=embed, mention_author=False)

async def get_information_embed(self, id, bot):
@staticmethod
async def get_information_embed(id, bot):
if isinstance(id, discord.Member):
return await Information_Embed.get_member_embed(bot, id)
elif isinstance(id, int):
Expand Down
9 changes: 6 additions & 3 deletions Cogs/memo.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,13 +83,15 @@ async def play_emoji_game(self, ctx):
except asyncio.TimeoutError:
await message.edit(embed=self.timeout_embed(), view=None)

def timeout_embed(self):
@staticmethod
def timeout_embed():
return discord.Embed(
title="Time's Up...",
description="||```You didn't click the emoji in time.```||",
)

def timestamp_gen(self, timestamp: int) -> str:
@staticmethod
def timestamp_gen(timestamp: int) -> str:
dt = datetime.utcfromtimestamp(timestamp).replace(tzinfo=timezone.utc)
formatted_timestamp = f"<t:{int(dt.timestamp())}:R>"
return formatted_timestamp
Expand Down Expand Up @@ -401,7 +403,8 @@ async def handle_error(self, interaction, error, title):
"""Handles errors and sends a custom embed."""
await error_custom_embed(self.bot, interaction, str(error), title=title)

async def validate_input(self, **kwargs):
@staticmethod
async def validate_input(**kwargs):
"""Validates input values to ensure they are not None or empty."""
for key, value in kwargs.items():
if value is None or value == "":
Expand Down
30 changes: 20 additions & 10 deletions Cogs/pokemon.py
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,8 @@ def process_image(self, path, filename):
}
self.cache[filename] = metadata

def evaluate_image_quality(self, image):
@staticmethod
def evaluate_image_quality(image):
"""Evaluates image quality based on sharpness."""
sharpness = cv.Laplacian(image, cv.CV_64F).var()
return sharpness
Expand All @@ -123,7 +124,8 @@ def cross_match(self, descriptors, image, k=2):

return best_match, max_accuracy

def evaluate_accuracy(self, matches):
@staticmethod
def evaluate_accuracy(matches):
"""Evaluates accuracy based on good matches."""
good_matches = sum(
1
Expand Down Expand Up @@ -321,15 +323,17 @@ async def download_image(self, session, pokemon_name, semaphore):
f"Image for {pokemon_name} already exists, skipping download."
)

def remove_srgb_profile(self, img_path):
@staticmethod
def remove_srgb_profile(img_path):
try:
with Image.open(img_path) as img:
img.save(img_path, icc_profile=None)
logger.debug(f"Removed sRGB profile from {img_path}")
except Exception as e:
logger.error(f"Error removing sRGB profile: {e}")

def ensure_correct_color_format(self, img):
@staticmethod
def ensure_correct_color_format(img):
"""
Convert image to RGB format.
"""
Expand All @@ -340,7 +344,8 @@ def ensure_correct_color_format(self, img):
return cv2.cvtColor(img, cv2.COLOR_RGBA2RGB)
return img

def download_file(self, url, filename):
@staticmethod
def download_file(url, filename):
response = urlopen(url)
with open(filename, "wb") as f:
f.write(response.read())
Expand Down Expand Up @@ -1717,7 +1722,8 @@ async def show_evolutions(self, interaction: discord.Interaction):
f"Error fetching Pokémon evolution chain: {str(e)}", ephemeral=True
)

async def get_pokemon_evolution_chain(self, pokemon_name):
@staticmethod
async def get_pokemon_evolution_chain(pokemon_name):
async with aiohttp.ClientSession() as session:
species_url = (
f"https://pokeapi.co/api/v2/pokemon-species/{pokemon_name.lower()}/"
Expand Down Expand Up @@ -1784,8 +1790,9 @@ async def display_evolution_chain(self, chain):

return embeds

@staticmethod
async def determine_evolution_method(
self, current_pokemon, evolution_details, next_pokemon
current_pokemon, evolution_details, next_pokemon
):
trigger = evolution_details.get("trigger", {}).get("name")
item = evolution_details.get("item")
Expand Down Expand Up @@ -2012,8 +2019,9 @@ def __init__(
def get_flag(self, lang):
return self.flag_mapping.get(lang)

@staticmethod
def get_pokemon_description(
self, pokemon_id, file_path="Data/pokemon/pokemon_description.csv"
pokemon_id, file_path="Data/pokemon/pokemon_description.csv"
):
try:
with open(file_path, mode="r", encoding="utf-8") as csv_file:
Expand All @@ -2030,8 +2038,9 @@ def get_pokemon_description(
return f"An error occurred: {e}"
return "Pokémon ID not found"

@staticmethod
def get_pokemon_region(
self, pokemon_id, file_path="Data/pokemon/pokemon_description.csv"
pokemon_id, file_path="Data/pokemon/pokemon_description.csv"
):
try:
with open(file_path, mode="r", encoding="utf-8") as csv_file:
Expand Down Expand Up @@ -2305,7 +2314,8 @@ async def get_pokemon_moves(self):
)
return moves_data

async def fetch_move_details(self, move_url):
@staticmethod
async def fetch_move_details(move_url):
response = requests.get(move_url)
if response.status_code == 200:
move_data = response.json()
Expand Down
12 changes: 8 additions & 4 deletions Cogs/quest.py
Original file line number Diff line number Diff line change
Expand Up @@ -397,7 +397,8 @@ async def shop(self, ctx):
except Exception as e:
await ctx.send(f"An error occurred while processing the shop: {e}")

def read_shop_file(self, filename):
@staticmethod
def read_shop_file(filename):
with open(filename, "r", encoding="utf-8") as file:
shop_data = json.load(file)
return shop_data
Expand Down Expand Up @@ -1029,7 +1030,8 @@ def _draw_text(self, draw, text_x, text_y):
fill=self.base_font_color,
)

def _download_image(self, url):
@staticmethod
def _download_image(url):
"""Download an image from a URL."""
try:
response = requests.get(url)
Expand Down Expand Up @@ -1084,7 +1086,8 @@ def __init__(self, bot):
async def handle_error(self, interaction, error, title):
await error_custom_embed(self.bot, interaction, str(error), title=title)

async def validate_input(self, **kwargs):
@staticmethod
async def validate_input(**kwargs):
for key, value in kwargs.items():
if value is None or value == "":
raise ValueError(f"{key} cannot be None or empty")
Expand Down Expand Up @@ -2669,7 +2672,8 @@ async def start(self, ctx):
except Exception as e:
await self.handle_error(ctx, e)

async def handle_error(self, interaction, exception):
@staticmethod
async def handle_error(interaction, exception):
traceback_msg = "".join(
traceback.format_exception(
type(exception), exception, exception.__traceback__
Expand Down
9 changes: 6 additions & 3 deletions Cogs/system.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,8 @@ def __init__(self, bot):
self.memory_check.start()
self.image_file = "Data/commands/help/help_embed_images.json"

async def get_latest_python_version(self):
@staticmethod
async def get_latest_python_version():
latest_version = (
subprocess.check_output(
[
Expand Down Expand Up @@ -117,7 +118,8 @@ def optimize_memory(self):
self.bot._connection.clear()
print(f"Optimized memory. Garbage collected: {collected} objects.")

def log_memory_usage(self):
@staticmethod
def log_memory_usage():
"""Logs the bot's current memory usage."""
process = psutil.Process(os.getpid())
memory_info = process.memory_info()
Expand All @@ -141,7 +143,8 @@ async def memory_info(self, ctx):
memory_usage = self.get_memory_usage()
await ctx.send(f"Current memory usage: {memory_usage:.2f} MB")

def get_memory_usage(self):
@staticmethod
def get_memory_usage():
"""Returns the current memory usage of the bot."""
process = psutil.Process(os.getpid())
memory_info = process.memory_info()
Expand Down
12 changes: 8 additions & 4 deletions Data/pokemon/dataset.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,8 @@ def __init__(self, db_file='Data/pokemon/pokemon_images.db', processed_file='Dat
print(f"Initializing processed entries database at {self.processed_file}...")
self._init_processed_db()

def _db_connect(self, db_name):
@staticmethod
def _db_connect(db_name):
return sqlite3.connect(db_name)

def _init_db(self):
Expand Down Expand Up @@ -183,15 +184,18 @@ def _process_image(self, image_path):
print(f"Error processing image {image_path}: {e}")
return None

def serialize_keypoints(self, keypoints):
@staticmethod
def serialize_keypoints(keypoints):
"""Convert cv2.KeyPoint objects to a serializable format."""
return [{'pt': kp.pt, 'size': kp.size, 'angle': kp.angle, 'response': kp.response, 'octave': kp.octave, 'class_id': kp.class_id} for kp in keypoints]

def deserialize_keypoints(self, serialized_keypoints):
@staticmethod
def deserialize_keypoints(serialized_keypoints):
"""Convert serialized keypoints back to cv2.KeyPoint objects."""
return [cv2.KeyPoint(kp['pt'][0], kp['pt'][1], kp['size'], kp['angle'], kp['response'], kp['octave'], kp['class_id']) for kp in serialized_keypoints]

def _clear_console(self):
@staticmethod
def _clear_console():
os.system("cls" if os.name == "nt" else "clear")

def _get_cache_items(self):
Expand Down
3 changes: 2 additions & 1 deletion Events/appearance.py
Original file line number Diff line number Diff line change
Expand Up @@ -178,7 +178,8 @@ async def update_grid_message(self, ctx, grid_index, total_pages):
logger.error(f"An error occurred while updating grid message: {e}")
raise

async def update_grid_reactions(self, message, grid_index, total_pages):
@staticmethod
async def update_grid_reactions(message, grid_index, total_pages):
try:
# Add reactions for image selection if there are any images
if total_pages > 1:
Expand Down
9 changes: 6 additions & 3 deletions Events/code_logger.py
Original file line number Diff line number Diff line change
Expand Up @@ -150,7 +150,8 @@ async def send_log_embed(self, message):
await const.error_custom_embed(self.bot, None, e, title="Log Embed Error")

# Method to send an embed message
async def send_embed(self, channel, title, description):
@staticmethod
async def send_embed(channel, title, description):
embed = discord.Embed(
title=title,
description=description,
Expand All @@ -163,13 +164,15 @@ async def send_embed(self, channel, title, description):
await channel.send(embed=embed)

# Method to send a file
async def send_file(self, channel, file_path, title, description):
@staticmethod
async def send_file(channel, file_path, title, description):
with open(file_path, "w") as file:
file.write(description)
await channel.send(file=discord.File(file_path), content=f"**{title}**")

# Method to get updated commands
async def get_updated_commands(self):
@staticmethod
async def get_updated_commands():
root_dir = os.getcwd()
repo = Repo(root_dir)
diff = repo.head.commit.diff(None)
Expand Down
12 changes: 8 additions & 4 deletions Events/poketwo_anti_thief.py
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,8 @@ def __init__(self, bot, anti_thief=None):
self.shiny_ping_phrase = load_ping_phrase()


def timestamp_gen(self, timestamp: int) -> str:
@staticmethod
def timestamp_gen(timestamp: int) -> str:
dt = datetime.datetime.utcfromtimestamp(timestamp).replace(tzinfo=datetime.timezone.utc)
return f'<t:{int(dt.timestamp())}:R>'

Expand Down Expand Up @@ -279,14 +280,16 @@ async def process_congratulations(self, congrats_message, original_message, refe
logger.error(f"Unexpected error in process_congratulations: {e}")
traceback.print_exc()

async def allow_all_to_catch(self, message):
@staticmethod
async def allow_all_to_catch(message):
embed = message.embeds[0]
embed.description = "✅ Everyone may catch the Pokémon now! No restrictions."
embed.color = 0x00FF00
await message.edit(embed=embed)
logger.info("Everyone is allowed to catch the Pokémon now.")

async def timeout_user(self, user, message):
@staticmethod
async def timeout_user(user, message):
BOT_TOKEN = os.getenv("TOKEN")
GUILD_ID = message.guild.id
USER_ID = user.id
Expand All @@ -312,7 +315,8 @@ async def timeout_user(self, user, message):
else:
logger.error(f"Failed to timeout user {user.mention}: {response.status_code}")

async def delete_embed_on_catch(self, message):
@staticmethod
async def delete_embed_on_catch(message):
try:
await message.delete()
logger.info("Embed deleted after successful catch.")
Expand Down
Loading

0 comments on commit 8a79903

Please sign in to comment.