Tuesday 15 July 2014

Python - null object pattern with generators -


It is insignificant to return the values, which can be considered as the 'incorrect' version of the successful return type , Such as if MyIterableObject: do_things () is an easy way to handle output or not, whether it is actually or not.

With the generator, bool (MyGenerator) is always True even if the lane in 0 or something equally Be empty So when I can write something like the following:

  results = list (get_generator (* my_variables)) if results: do_stuff (result)  

It seems as if the benefit of being a generator in the first place is dashed.

Maybe I am not doing just one language or doing anything, but clearly what is the creation of Python language, it is not to be done with empty generators?

To be clear, I want to be able to give some insight to the user so that the script can actually work (if any) - the reference snippet is as follows:

 < Code> # python 2.7 templates = files_from_folder (path_to_folder) results = list (get_same_sections (templates)) # Generator returns when the results are not found: msg (Sys.exit () results for "data is not synced."): I, for zip (data, template) tpl: tpl ['sections'] [i] ['uuid'] = data [-1] msg ("{} min D. Found to sync. "Format (len (result)))  

This works, but I think that last time it is a waste that changes the generator in the list For just to see if there is any work, then I think there is a better way, yes?

EDIT: I understand that the generator is not yet to be used like this, but I will add an example to show my logic.

There is a semi-popular 'helper function' in Python, which you see now and again when you have a structure such as a nested dict or what-usually you Getnode is called or getn , whenever I see it, it reads something like this:

  def get_node (seq, path): P on the way: If se in se: seq = seq [p] and: return () return seq  

So this way, it can make it easier to deal with your results Are always any try / except without the complicated path to the data in the nested structure to check when you actually "do not work with some extraordinary '.

 

It looks at least as if syntax (or maybe) exists with the generator, without writing a class, thus handling the generator As the suggestion has been given.

A generator does not have a length of time until its end is over. / P>

The only way is whether or not this is found, This exhaust is

  item = list (myGenerator) if item: #Some  

Unless you have the attribute nonzero , Which internally sees the list of your iterations

  class MyGenerator (object): def __init __ (self, item): self.items = item def __iter __ (self ): For myself. I.e. Items: produce i def __nonzero __ (self): return bool (self.items) & gt; & gt; boole (migrant ([]) false & gt; & Gt; & Gt; Boole (Mizenator ([1]); true & gt; & Gt; & Gt;  

No comments:

Post a Comment