Argument checking in Python generators -
is there way check arguments in python generator , have exception raised instead of having generator object returned?
consider following function example:
def find_files(directory, pattern="*"): if not os.path.isdir(directory): raise valueerror("invalid directory: " + directory) root, _, files in os.walk(directory): basename in files: if fnmatch.fnmatch(basename, pattern): yield os.path.join(root, basename) when creating generator object,
g = find_files('/non/existent/path') an exception not raised if path '/non/existent/path' not exist. however, when using generator (iterating through g), later in code, error thrown.
i'd prefer have error thrown when attempting create generator object instead.
the way know of wrap (non-checking) generator in function checking:
def _find_files(directory, pattern): root, _, files in os.walk(directory): basename in files: if fnmatch.fnmatch(basename, pattern): yield os.path.join(root, basename) def find_files(directory, pattern="*"): if not os.path.isdir(directory): raise valueerror("invalid directory: " + directory) return _find_files(directory, pattern) the reason generator (by definition) doesn't execute until next (__next__ in python3.x) method called. @ point, executes code first yield , stops executing until next time .next() called , on.
the above solution pretty general concept can used checking stuff before generator starts -- and, barring pretty intense introspection, should able used drop in replacement generators sort of thing might necessary.
Comments
Post a Comment