> raise TypeError(f"iterable cannot be a str")
Why is that a f-string? It's a static message. That's kind of like
writing `x += eval('1')`.
Well I had cut it down from another copy/pasted version with a variable in it just for this conversation.
> yield from iter(iterable)
That would be better written as `return iter(iterable)`, and possibly
more efficient too (I think).
Thanks.
> The nature of my coding work is a lot of parsing of different kinds of text
> files and so I've had to write a lot of functions that are meant to take in
> an iterable of strings. So the biggest context that comes to mind is to
> guard against future me mistakenly sending a string into functions that are
> intended to work with iterables of strings.
Have you considered writing the functions to accept either a single
string or an iterable of strings?
Well these are parsing FILES- not only iterables of strings but iterables of LINES- but there are certainly times when that would be useful.
Assuming they all take a single iter-of-strings argument as first
argument, you could do that with a simple decorator:
def decorate(func):
@functools.wraps(func)
def inner(iter_of_strings, *args, **kw):
if isinstance(iter_of_strings, str):
iter_of_strings = (iter_of_strings,)
return func(iter_of_strings, *args, **kw)
return inner
The decorator idea is much more idiomatic python. Thanks for the suggestion.
However in these kinds of situations if I ever were accidentally sending in a string, it is much more likely I meant to split it on lines and need to do this:
if isinstance(iter_of_strings, str): iter_of_strings = iter_of_strings.split("\n") But I've also found that if I try to predict what I meant to do, instead of just reporting that I did something that doesn't seem to make sense, I'm making a mistake... Better just to create the exception and remind myself that it is not expecting a string...