How to create functors?

Ned Deily nad at acm.org
Tue Aug 18 16:46:57 EDT 2009


In article 
<c217c4a4-b891-469e-af4f-4e44e2c95748 at z24g2000yqb.googlegroups.com>,
 Robert Dailey <rcdailey at gmail.com> wrote:
> On Aug 18, 3:31 pm, Duncan Booth <duncan.bo... at invalid.invalid> wrote:
> > Robert Dailey <rcdai... 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?
> >
> > def print1():
> >     print "Foobar"
> >
> > It looks like in your version of Python "print" isn't a function. It always
> > helps if you say the exact version you are using in your question as the
> > exact answer you need may vary.
> 
> I'm using Python 2.6. And using the legacy syntax in the lambda does
> not work either. I want to avoid using a def if possible. Thanks.

The problem is that in Python 2 print is a statement, not a function.  
That should work fine in Python 3 where print *is* a function.  In 2.x, 
you can wrap print in a function or use something like:

>>> import sys
>>> print1 = lambda: sys.stdout.write("Foobar\n")
>>> print1()
Foobar

or the pprint library module or various other solutions.

-- 
 Ned Deily,
 nad at acm.org




More information about the Python-list mailing list