I was tasked with writing a python script to check if a passed ID number exists within a file. The file I was give contains roughly 25,000 unique ID numbers. An ID number is a unique 9 digit number.
I have a couple specific things for you to comment on if you decide to review this:
As it stands, I convert the
user_idpassed in the
str. I do this because I need the ID number to be the same type when I read the ID's from the file. Is there an easier way to accomplish this?
This is my first time using a PEP 484 type hint,
Generator. Am I using it correctly?
This is also my first time utilizing a generator in this fashion. I used a generator here because instead of loading the entire file into memory, storing in a list, then iterating over the list, I can read each line and can exit early if an ID is found. Is it good that I'm using it in this way, or is there an easier way to do this?
Using a helper function is a new concept to me. Am I utilizing this helper function in the most pythonic way?
Of course, any constructive criticism beyond these points is welcome. Thanks in advance.
""" Ensures id number matches any within the ID file. An ID number is a unique 9 digit number. """ import random import time from typing import Union, Generator def id_exists(user_id: Union[int, str]) -> bool: """ Determines if the passed ID exists within the ID file. The ID passed must be of length 9 exactly, and only contain numbers. :param Union[int, str] user_id: User ID to check for existence :return bool: True if ID exists in file, False otherwise """ # Generator[yield_type, send_type, return_type] # def get_ids() -> Generator[str, None, None]: """ Helper function for `id_exists`. Yields each line in the ID file. :return Generator[str, None, None]: Lines in ID file. """ with open("ids.txt", "r") as file: for line in file: yield line.strip() # Convert user_id to <class 'str'> if not already # if type(user_id) == int: user_id = str(user_id) # Ensure user_id matches specifications # if len(user_id) != 9 or not user_id.isdigit(): raise ValueError("ID should be 9 characters long and all digits.") # Check ID against file and return result # return any(user_id == stored_id for stored_id in get_ids())