@@ -196,50 +196,38 @@ def write(self, path=None, mode='w'):
196196 :param path: override the write path
197197 :return: Dictionary containing counts
198198 """
199- written_count = 0
200- comments_written = 0
201- blanks_written = 0
202- ipv4_entries_written = 0
203- ipv6_entries_written = 0
204- if path :
205- output_file_path = path
206- else :
207- output_file_path = self .path
199+
200+ counters = {
201+ 'total_written' : 0 ,
202+ 'comments_written' : 0 ,
203+ 'blanks_written' : 0 ,
204+ 'ipv4_entries_written' : 0 ,
205+ 'ipv6_entries_written' : 0 ,
206+ }
207+ output_file_path = path if path else self .path
208208 try :
209209 with open (output_file_path , mode ) as hosts_file :
210- for written_count , line in enumerate ( self .entries ) :
211- if line .entry_type == 'comment' :
212- hosts_file .write (line .comment + "\n " )
213- comments_written += 1
214- if line .entry_type == 'blank' :
210+ for entry in self .entries :
211+ if entry .entry_type == 'comment' :
212+ hosts_file .write (entry .comment + "\n " )
213+ counters [ ' comments_written' ] += 1
214+ elif entry .entry_type == 'blank' :
215215 hosts_file .write ("\n " )
216- blanks_written += 1
217- if line .entry_type == 'ipv4' :
218- hosts_file .write (
219- "{0}\t {1}{2}\n " .format (
220- line .address ,
221- ' ' .join (line .names ),
222- " # " + line .comment if line .comment else ""
223- )
224- )
225- ipv4_entries_written += 1
226- if line .entry_type == 'ipv6' :
216+ counters ['blanks_written' ] += 1
217+ else :
227218 hosts_file .write (
228219 "{0}\t {1}{2}\n " .format (
229- line .address ,
230- ' ' .join (line .names ),
231- " # " + line .comment if line .comment else ""
220+ entry .address ,
221+ ' ' .join (entry .names ),
222+ " # " + entry .comment if entry .comment else "" ,
232223 )
233224 )
234- ipv6_entries_written += 1
225+ key = 'ipv6_entries_written' if entry .entry_type == 'ipv6' else 'ipv4_entries_written'
226+ counters [key ] += 1
227+ counters ['total_written' ] += 1
235228 except Exception :
236229 raise UnableToWriteHosts ()
237- return {'total_written' : written_count + 1 ,
238- 'comments_written' : comments_written ,
239- 'blanks_written' : blanks_written ,
240- 'ipv4_entries_written' : ipv4_entries_written ,
241- 'ipv6_entries_written' : ipv6_entries_written }
242-
230+ return counters
243231 @staticmethod
244232 def get_hosts_by_url (url = None ):
245233 """
@@ -264,8 +252,10 @@ def exists(self, address=None, names=None, comment=None):
264252 if self .find_all_matching (address = address , name = name , comment = comment ):
265253 return True
266254
267- return any (entry .entry_type == 'comment' and entry .comment == comment
268- for entry in self .entries )
255+ if comment :
256+ return any (entry .entry_type == 'comment' and entry .comment == comment
257+ for entry in self .entries )
258+ return False
269259
270260 def remove_all_matching (self , address = None , name = None , comment = None ):
271261 """
0 commit comments