Python: Using the same function as both a generator and a regular function -


is possible use function both regular function (that stuff , returns) , generator function?

suppose have following code:

    def __init__(self):         self.make_generator = false      def foo(self):         gen = (x x in my_list)         x in gen:             # stuff                 if self.make_generator:                     yield         # return raise stopiteration         return 

the idea here if self.make_generator false, don't want foo yield; want not generator can call like:

    foo() 

and if wanted yield between iterations, i'd make generator so:

    def __init__(self):         self.make_generator = true         self.foo_gen = self.foo()      def run(self):         while true:             self.foo_gen.next() 

but seems not possible. want keep code dry not sure how can control when foo generator , when executes regular function.

thanks!


Comments

Popular posts from this blog

java - Custom OutputStreamAppender not run: LOGBACK: No context given for <MYAPPENDER> -

java - UML - How would you draw a try catch in a sequence diagram? -

c++ - No viable overloaded operator for references a map -