On Sun, Feb 23, 2020 at 12:10:24AM -0500, Ricky Teachey wrote:

> I've only been at it for about 3 years, but because of iterable strings I
> always seem to regret not using a function like this in many contexts:
> 
> def iter_nostr(iterable):
>     if isinstance(iterable, str):

>         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')`.


>     yield from iter(iterable)

That would be better written as `return iter(iterable)`, and possibly 
more efficient too (I think).


> 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?

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



-- 
Steven
_______________________________________________
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/PECIADWI67ETFAPJ7TIP7BW4ZVPE6JG3/
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to