How to create functors?
Rami Chowdhury
rami.chowdhury at gmail.com
Tue Aug 18 16:57:54 EDT 2009
> why am I able to use print as a
> function in general-purpose code in my Python 2.6 script
I believe it's because that is parsed as the print statement followed by a
parenthesized expression.
On Tue, 18 Aug 2009 13:42:59 -0700, Robert Dailey <rcdailey at gmail.com>
wrote:
> On Aug 18, 3:40 pm, Chris Rebert <c... at rebertia.com> wrote:
>> On Tue, Aug 18, 2009 at 1:32 PM, Robert Dailey<rcdai... 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.
>>
>> chris at morpheus ~ $ python
>> Python 2.6.2 (r262:71600, May 14 2009, 16:34:51)
>> [GCC 4.0.1 (Apple Inc. build 5484)] on darwin
>> Type "help", "copyright", "credits" or "license" for more
>> information.>>> print1 = lambda: print( "Foobar" )
>>
>> File "<stdin>", line 1
>> print1 = lambda: print( "Foobar" )
>> ^
>> SyntaxError: invalid syntax>>> from __future__ import print_function
>> >>> print1 = lambda: print( "Foobar" )
>> >>> print1()
>>
>> Foobar
>>
>> Cheers,
>> Chris
>> --http://blog.rebertia.com
>
> I see what you're saying now. However, why am I able to use print as a
> function in general-purpose code in my Python 2.6 script, like so:
>
> def SomeFunction():
> print( "Hello World" )
>
> But, I am not able to do this:
>
> SomeFunction = lambda: print( "Hello World" )
>
> ??????
>
> Doesn't make sense.
--
Rami Chowdhury
"Never attribute to malice that which can be attributed to stupidity" --
Hanlon's Razor
408-597-7068 (US) / 07875-841-046 (UK) / 0189-245544 (BD)
More information about the Python-list
mailing list