Why not real anonymous functions?

If you are ok with using a not well known idiom, you can already do this:

T = TypeVar('T')

def init(func: Callable[[], T]) -> T:
    return func()
    

@init
def data() -> SomeDataType:
    package = get_thing()
    assert packet.valid()
    return package.payload

data is now such a constant. Type checkers should already understand it, although PyCharm doesn’t like it, but that is something that the IDE devs should fix.

You can then also name the function _ to signal that it shouldn’t be used to get a quick local scope:

def scope(func: Callable[[], None]) -> None:
    return func()

@scope
def _():
    ...

I guess the pattern isn’t all that common because the need for it isn’t that high. Most of the time just executing the code and optionally del the temporary variables is enough.

Also, IMO you are failing to understand the primary opposition. It isn’t that there aren’t good usecases. It’s that we don’t know of an acceptable syntax (C++ is bracket based, so it doesn’t translate well) or of usecase so overwhelming strong that a complete break in python’s syntactic structure is acceptable. (neither of the two you mention clear that bar IMO)

3 Likes