[New-bugs-announce] [issue38940] Add a new functools.cast() function

Ugra Dániel report at bugs.python.org
Fri Nov 29 06:30:18 EST 2019


New submission from Ugra Dániel <daniel.ugra at gmail.com>:

In some cases it would be really helpful to have a decorator which automagically casts returned value to a different type.

Particularly, instead of writing something like this:

def example():
    result = []

    for ...:
        result.append(item)

    return result

...this would do the magic:

@functools.cast(list)
def example():
    for ...:
        yield item

On the positive side (apart from its compactness) when an implementation changes from list to set, .append() does not need to be changed to .add().

Of course on the caller side one can always write list(example()) but sometimes this transformation needs to be done on implementation side for architectural reasons.

Pseudocode for proposed functools.cast():

def cast(type):
    def wrapper(func):
        @wraps(func)
        def newfunc(*args, **keywords):
            return type(func(*args, **keywords))

        return newfunc

    return wrapper

----------
components: Library (Lib)
messages: 357640
nosy: daniel.ugra
priority: normal
severity: normal
status: open
title: Add a new functools.cast() function
type: enhancement
versions: Python 3.9

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue38940>
_______________________________________


More information about the New-bugs-announce mailing list