Python Forum

Full Version: how to test if an object came from os.walk()
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
i am writing a function that is to be given an object that came from os.walk(). i like to do thorough error checks in code i write, at least for final release. os.walk() returns a generator. is there a way to be more specific and detect that the given object is a generator from os.walk() as opposed to some other kind of generator? should i even be trying to do this and, instead, allow callers to pass a generator that looks and quacks like a generator from os.walk()?

how would you go about testing for just a generator, since

isinstance(foo,generator)
does not work, because generator is not defined. is there something i can import to get this definition, or should i just do

isinstance(foo,type(os.walk()))
?
import os
import types


isinstance(os.walk('.'), types.GeneratorType) # True
isinstance(os.walk, types.GeneratorType) # False
If you want to check, if it comes from os.walk, you can check for the __name__.
But I think it's not a good style to check for __name__.
inspect.isgenerator(gen_obj) will work too but I don't know how can check if comes from os.walk
so, i'd have to get the generator to yield one or more results and see if they look OK. maybe just one, so i can still modify it if i need to. then i would look to see if i get a 3-tuple with (string,list,list). the simplest way to do this is probably apply that check each time and raise TypeError if it is not.

i am writing a generator to fully flatten the tree. i have many use cases for flat trees. i will probably have a number of callbacks to apply caller tests (i hope a generator lets me do that).