3

How to make Self-Invoking Anonymous Functions in Python?

For example with JavaScript:

Standard way:

function fn (a) {
   if (a == 1) {
      alert(a);
   }
   else {
     alert(0);
   }
  /...
}

fn(1);

Self-Invoking Anonymous call:

!function(a) {
   if (a == 1) {
      alert(a);
   }
   else {
     alert(0);
   }
   /...
}(1);

Are there any analogues in Python?

5
  • @Marcin, just wondering) Commented Feb 18, 2012 at 16:07
  • That first case is not anonymous. Neither of them are "self-invoking" in any sense. I edited the title. Commented Feb 18, 2012 at 18:11
  • @Opsa: "just wondering" does not make a bad question become magically good. Please explain what the use case is. Commented Feb 19, 2012 at 0:13
  • @S.Lott I suppose that it might make it easier to port JavaScript libraries to Python, since many JavaScript libraries use this pattern. Commented Aug 8, 2013 at 19:16
  • In 2017, the main use case I use this for is to prebind/freeze the values of a datastucture (like a dict) that is meant to be imported from inside another module without having to assign/define an actual function or explicitly pickle: STATIC_CONST_D = (lambda S: {x: transform(x) for x in S})(set(1,2,3)) from module import STATIC_CONST_D Commented Mar 14, 2018 at 22:13

5 Answers 5

7

I don't think is possible, given your comments to the lambda answers. The lambda operator is Python's only way of supporting anonymous functions. If you need to support statements, then you need to use a def, which always must be named.

Keep in mind that lambdas can support limited if-then logic, however. The following two are lambda expressions that implements the if-then logic given above:

(lambda a: alert(1 if a == 1 else 0))(1)

More literally:

(lambda a: alert(a) if a == 1 else alert(0))(1)
Sign up to request clarification or add additional context in comments.

Comments

5

If your function is simple and only has expressions (no statements), then you can use lambda to create anonymous functions and call them inline.

>>> (lambda x, y: x*y)(3, 5)
15

5 Comments

I know about lambda's. However, I am interested in the use of statements within functions as well
@Opsa: Python does not have full anonymous functions, to a large extent because there is no usecase for them outside obfuscation.
@LennartRegebro The use-case is isolating a namespace for a block of code that you need to execute but whose variables will not be used outside the block. Also, being able to exit the function by returning at any point can avoid multiple levels of indentation that would otherwise be necessary in some cases.
@kloddant Yes, that's two use cases for functions. You are correct. There is no benefit to having the function being anonymous. At least not in Python, in other languages functions may be broken in some way that I'm not aware of.
Let me clarify then. The benefit is that you can declare and run the function all in one step, without having a separate declaration beforehand, which would both look messy but more importantly introduce ambiguity into your intent, so that future programmers would not know if the function is meant to be able to be used elsewhere. Yes, you can use underscore prefixes for this, but you still have a separately-declared, single-use function that could technically be reused. Regular functions are meant for reuse. Anonymous functions are meant to be single-use namespaces within codeblocks.
3

You could use a named function and unbind its name after using it like:

def hello(there):
    print there
hello("france")
del hello

Comments

2

Yes (Python 3 or Python 2 using from __future__ import print_function):

(lambda x: print(x))('foo')

But using lambda you can only write a single line of code.

2 Comments

to be precise, you can only use lambda to turn an expression into a function. normal defed functions are permitted to use "lines" of code, what in the python grammar is called a suite. That's why it's necessary to use the print function, because that can be used as part of an expression, where the print statement cannot be used that way.
You can use expressions - not statements. If you want to hack in multiple expressions, you may do that, for example, making the lambda function generate a tuple, each term of which is one expression. Ex.:lambda a: (thing1(), thing2(), thing3())
1

You can always abuse exec, passing your code as a string:

def anon(code):
    execdict = {}
    exec('def f():{}'.format(code), execdict)
    return execdict['f']

anon("print('hello'); print('hello again')")()

(this works in python 3, I think exec behaves very differently in earlier versions)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.