python - Where best to put the generator.close()? -
i buildt class morning , works sweet , tight since works calling fresh generator every time i'm concerned i'm leaving bunch in memory. i'd love right after yield statement finally. seem little cleaner.
class enter: def __init__(self,entries, container=[], keyname = "key", valuename = "value"): self.dict = {} self.entries = entries self.container = container self.keyname = keyname self.valuename = valuename def gen(self,dis): print(dis) yield input("entry: ") def enter(self): ea in range(self.entries): print("\nplease input a", self.keyname, "then a", self.valuename) x = next(self.gen("\nenter " + self.keyname + ":")) y = next(self.gen("\nenter " + self.valuename + ":")) self.dict.update({x:y}) retrun self.dict def enterlist(self): lst = [] ea in range(self.entries): print("\nsome message") x = next(self.gen("\nenter: ")) lst.append(x) if self.container == (): lst = tuple(lst) return lst dictionary = enter(entries = 2, keyname = "first name", valuename="lastname").enter() print(dictionary) output = enter(entries = 3, container= () ).enterlist() print(output)
judging code style i'd you're java programmer giving python whirl.
welcome python, chose right version :)
one of cool things python have concerned memory leaks. python uses reference counting make sure inaccessible objects garbage collected.
in x = next(self.gen("\nenter " + self.keyname + ":"))
3 important things happen:
gen(self,dis)
called, returning generator objectnext(gen)
moves generator next yield statementyield input("entry: ")
, returns yielded value. note not cause generator exit has yet reach return or end of function. calling next(gen) again (and raisestopiteration
)- the returned value bound
x
whilst generator object has become inaccesible (it has no variable left bound it). generator object therefor deleted python garbage collector.
this said, agree others saying generator inappropriate application. not because of overhead - highly doubt generator instantiation cause noticable overhead in applications - because application very simple.
in addition code easier read if simplified to
def gen(self,dis): print(dis) return input("entry: ") def enter(self): ea in range(self.entries): print("\nplease input a", self.keyname, "then a", self.valuename) x = self.gen("\nenter " + self.keyname + ":") y = self.gen("\nenter " + self.valuename + ":") self.dict.update({x:y}) retrun self.dict
generally python best when written idiomatically
Comments
Post a Comment