How to create functors?

Jerry Hill malaclypse2 at gmail.com
Tue Aug 18 22:49:34 CEST 2009


On Tue, Aug 18, 2009 at 4:27 PM, Robert Dailey<rcdailey at gmail.com> wrote:
> Hello,
>
> I want to simply wrap a function up into an object so it can be called
> with no parameters. The parameters that it would otherwise have taken
> are already filled in. Like so:
>
>
>      print1 = lambda: print( "Foobar" )
>      print1()
>
> However, the above code fails with:
>
>  File "C:\IT\work\distro_test\distribute_radix.py", line 286
>    print1 = lambda: print( "Foobar" )
>                         ^
> SyntaxError: invalid syntax
>
> How can I get this working?

You can't, at least not with that example.  Lambdas are restricted to
a single expression[1]. Print is not an expression, it's a
statement[2].

I'm guessing that your use case is not really in wrapping a print
statement in an anonymous function. Given the first part of your
message, you might find something of use in the functools module,
particularly functools.partial [3].

1: http://docs.python.org/tutorial/controlflow.html#lambda-forms
2: http://docs.python.org/reference/simple_stmts.html
3: http://docs.python.org/library/functools.html#functools.partial

-- 
Jerry



More information about the Python-list mailing list