Self executing functions in python

Regarding the second half of the question

is there a better way to implement a self-executing function?

The standard way (<function-expression>)() is not possible in Python, because there is no way to put a multi-line block into a bracket without breaking Python's fundamental syntax. Nonetheless, Python do recognize the need for using function definitions as expressions and provide decorators (PEP318) as an alternative. PEP318 has an extensive discussion on this issue, in case someone would like to read more.

With decorators, it would be like

evalfn = lambda f: f()

@evalfn
def _():
    print('I execute immediately')

Although vastly different syntatically, we shall see that it really is the same: the function definition is anonimous and used as an expression.

Using decorator for self-excuting functions is a bit of overkill, compared to the let-call-del method shown below. However, it may worth a try if there are many self-execution functions, a self-executing function is getting too long, or you simply don't bother naming these self-executing functions.

def f():
    print('I execute immediately')
f()
del f

You don't do it. It's a good in JavaScript, but in Python, you haven either lightweight syntax nor a need for it. If you need a function scope, define a function and call it. But very often you don't need one. You may need to pull code apart into multiple function to make it more understandable, but then a name for it helps anyway, and it may be useful in more than one place.

Also, don't worry about adding some more names to a namespace. Python, unlike JavaScript, has proper namespaces, so a helper you define at module scope is not visible in other files by default (i.e. unless imported).


For a function A that will be called only in a specific function B, you can define A in B, by which I think the namespace will not be polluted. e.g.,

Instead of :

def a_fn():
    //do something
def b_fn():
    //do something
def c_fn():
    b_fn()
    a_fn()

You can:

def c_fn():
    def a_fn():
        //do something
    def b_fn():
        //do something
    b_fn()
    a_fn()

Though I'm not sure if its the pythonic way, I usually do like this.