I'm working on a Python 3 program which will implement sequential access master files. I have the code to open the files working fine, and I found myself using a sentinel value to guard against an empty master file (after I have iterated through each line). Is there a more pythonic way to guard against empty lists?
translist
is a list of the transactions (ie 1 Brown 123 Main St.).
masterlist
is a list of the current name-address pairs in the master file (ie Charlie 134 South St.).
Do not hesitate to criticize my python, this is the first non-throwaway program I've written in it. Also, this program is not finished, I'm still planning to implement modify and delete.
while(translist): #is not empty
currentTransactions = [] #reset current transaction list
currentTransactions.append(translist.pop(0)) #get the first transaction
name = getName(currentTransactions[0])
#collect all transactions with same name
for item in translist:
if(getName(item) in name): #if names match
currentTransactions.append(item) #add to the list of current transactions
#then filter out the current transactions from the transactions list
translist = [line for line in translist if line not in currentTransactions]
#get ready to apply the current transaction
if(masterlist):
currentRecord = masterlist.pop(0)
else: #the code should continue, but only insertions are valid
currentRecord = -1 #sentinel value
continue
delete = bool() #false
if(currentRecord == -1 or getName(currentRecord) > name):
thisTransaction = currentTransactions.pop(0) #get the first transaction
thisType = getTransactionType(thisTransaction) #and its type
if(thisType == "insert"):
masterlist = currentRecord.append(masterlist) #sticks the current record back on the front
currentRecord = format(thisTransaction) #then prep for writing
while(currentRecord != -1 and getName(currentRecord) < name): #while the name in the master list is not in our transactions
masterfile.write(currentRecord) #write it
if masterlist: #is not empty
currentRecord = masterlist.pop(0) #then move on to the next
if not delete:
masterfile.write(currentRecord)
Thanks in advance! Post if you need any more information or the full code from the program.
bool()
withFalse
, for starters. There's also PEP 8, the style guide, to look at; some important matters with it areif X:
rather thanif(X):
,variable_name
rather thanvariableName
. As for yourcurrentRecord
, useNone
and checkcurrent_record is None
/current_record is not None
rather than-1
collections.deque
in that case.