473,574 Members | 2,511 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

anonymous function objects?

Is it possible to specify anonymous functions, something like:
f = {print "hello world"}
f()

hello world
in Pyton?
Lambda expressions don't work here.

Thanks,
Uwe

Jul 19 '05 #1
8 1706
Uwe Mayer <me*****@hadiko .de> writes:
f = {print "hello world"}
f()
hello world

in Pyton? Lambda expressions don't work here.


Closest you can come is:

f = lambda: sys.stdout.writ e("hello world\n")

Of course if you're trying to capture the function in a named variable
like f, just use a def statement.
Jul 19 '05 #2
Friday 29 April 2005 00:06 am Paul Rubin wrote:
Closest you can come is:

f = lambda: sys.stdout.writ e("hello world\n")
Ah. :))
Why does the "print" statement return a syntax error here?
lambda: print("hallo") File "<stdin>", line 1
lambda: print("hallo")
^
SyntaxError: invalid syntax
Of course if you're trying to capture the function in a named variable
like f, just use a def statement.


Unfortunately I want to assign a handler function to an object and something
like this does not work:
class Foobar(object): pass .... a = Foobar()
def a.handler():

File "<stdin>", line 1
def a.handler():
^
SyntaxError: invalid syntax

But wrapping print into a myprint function works :)
Thanks,
Ciao
Uwe
Jul 19 '05 #3
Uwe Mayer ha scritto:
Friday 29 April 2005 00:06 am Paul Rubin wrote:
Closest you can come is:

f = lambda: sys.stdout.writ e("hello world\n")

Ah. :))
Why does the "print" statement return a syntax error here?
^^^^^^^^^


this is the reason :)
You can't have statements into an expression
Jul 19 '05 #4
Uwe Mayer wrote:
Unfortunately I want to assign a handler function to an object and something
like this does not work:
class Foobar(object): pass
...
a = Foobar()
def a.handler():
File "<stdin>", line 1
def a.handler():
^
SyntaxError: invalid syntax


But this does work, or something close to it:
class Foobar(object): pass .... def handler(self): .... print 'in handler'
.... f = Foobar()
f.handler() Traceback (most recent call last):
File "<stdin>", line 1, in ?
AttributeError: 'Foobar' object has no attribute 'handler'
import new
f.handler = new.instancemet hod(handler, f)
f.handler()

in handler
-Peter
Jul 19 '05 #5
Uwe Mayer:
Why does the "print" statement return a syntax error here?


Google for "Python regrets" where Guido admits that
'print' should have been a function.

Michele Simionato

Jul 19 '05 #6
Friday 29 April 2005 05:40 am Michele Simionato wrote:
Uwe Mayer:
Why does the "print" statement return a syntax error here?


Google for "Python regrets" where Guido admits that
'print' should have been a function.


:) Will this change in future - and if not, why not?

Ciao
Uwe
Jul 19 '05 #7
On Thu, 28 Apr 2005 20:57:51 -0400, Peter Hansen <pe***@engcorp. com> wrote:
Uwe Mayer wrote:
Unfortunately I want to assign a handler function to an object and something
like this does not work:
>class Foobar(object): pass


...
>a = Foobar()
>def a.handler():


File "<stdin>", line 1
def a.handler():
^
SyntaxError: invalid syntax


But this does work, or something close to it:
class Foobar(object): pass... def handler(self):... print 'in handler'
... f = Foobar()
f.handler()Traceback (most recent call last):
File "<stdin>", line 1, in ?
AttributeError : 'Foobar' object has no attribute 'handler'
import new
f.handler = new.instancemet hod(handler, f)
f.handler()in handler


Or you can doctor up a Foobar that treats all
function attributes of its instances as methods
to be bound to the specific instance, e.g.,
(not tested beyond what you see)
class Foobar(object): ... def __getattribute_ _(self, attr):
... sentinel = object()
... atto = object.__getatt ribute__(self, '__dict__').get (attr, sentinel)
... if hasattr(atto, '__get__'): return atto.__get__(se lf, type(self))
... elif atto is sentinel: return object.__getatt ribute__(self, attr)
... return atto
... f = Foobar()
def handler(self): print 'handler of:', self ... f.handler = handler
f.handler() handler of: <__main__.Fooba r object at 0x02F0428C> f <__main__.Fooba r object at 0x02F0428C> f.handler <bound method Foobar.handler of <__main__.Fooba r object at 0x02F0428C>> f.h Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<stdin>", line 6, in __getattribute_ _
AttributeError: 'Foobar' object has no attribute 'h' f.h =123
f.h 123 f.f2 = lambda self: 'Hi'
f.f2 <bound method Foobar.<lambda> of <__main__.Fooba r object at 0x02F0428C>> f.f2() 'Hi' Foobar.ordinary _method = lambda self: 'ordinary'
f.ordinary_meth od <bound method Foobar.<lambda> of <__main__.Fooba r object at 0x02F0428C>> f.ordinary_meth od() 'ordinary'

Try another Foobar instance:
g = Foobar()
g.ordinary_meth od() 'ordinary' g.handler Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<stdin>", line 6, in __getattribute_ _
AttributeError: 'Foobar' object has no attribute 'handler' def g_handler(self) : print "g's own handler for", self ... g.alias = g_handler
g.alias() g's own handler for <__main__.Fooba r object at 0x02EF134C>

BTW new.instancemet hod(handler, f) seems to duplicate handler.__get__ (f),
leaving out the type(f) in handler.__get__ (f, type(f)) that would make a bound method,
which is what it is, and which could be set as attribute of anything.

Note the difference between newh which sticks with the f
passed to new.instancemet hod, and real, which Foobar.__getatt ribute__
dynamically attaches to the selected instance:
import new
f.newh = g.newh = new.instancemet hod(lambda self:('newh', self), f)
f.real = g.real = lambda self:('real', self)
f.newh() ('newh', <__main__.Fooba r object at 0x02F0428C>) g.newh() ('newh', <__main__.Fooba r object at 0x02F0428C>) f.real() ('real', <__main__.Fooba r object at 0x02F0428C>) g.real() ('real', <__main__.Fooba r object at 0x02EF134C>)
^^^^^^^^^^

IOW, a plain callable has __get__ and gets bound to the instance,
whereas a bound method doesn't have __get__ any more, so it gets
retrieved as a plain attribute. BTW, to get an ordinary function call
for a function attribute of a Foobar instance, you'd have to
eliminate the function's __get__ effect one way or another,
e.g. staticmethod (which really wraps the function with a descriptor,
substituting its own __get__, which Foobar.__getatt ribute__ uses transparently)
def sm(firstarg='sm first arg', *args): return firstarg, args ... g.sm = staticmethod(sm )
g.sm() ('sm first arg', ()) g.sm <function sm at 0x02EE8E9C> g.__dict__['sm'] <staticmethod object at 0x02E8177C> g.__dict__['sm'].__get__ <method-wrapper object at 0x02F0476C> g.__dict__['sm'].__get__(g)

<function sm at 0x02EE8E9C>

Regards,
Bengt Richter
Jul 19 '05 #8
I have not access to Guido's time machine!

M. S.

Jul 19 '05 #9

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

76
3723
by: Nick Coghlan | last post by:
GvR has commented that he want to get rid of the lambda keyword for Python 3.0. Getting rid of lambda seems like a worthy goal, but I'd prefer to see it dropped in favour of a different syntax, rather than completely losing the ability to have anonymous functions. Anyway, I'm looking for feedback on a def-based syntax that came up in a...
6
3443
by: Mark Brandyberry | last post by:
I have a bit of a problem with an overloaded operator that I'm writing that I have distilled down to an example in the code below. Essentially, I have an operator function (+=) that takes a reference parameter of class Poly. If I use it with a named object (of type Poly), as in: P1+=P4; where P1 and P4 are both local variables of the...
11
3278
by: G Fernandes | last post by:
I've heard some mention "anonymous" objects in c.l.c and other places (conversations), and I was wondering what exactly these are. Anonymous seems to imply that there is no name, but no name implies that one can't access the object, which implies that the object would be useless. So what exactly are they?
5
1760
by: dhtml | last post by:
On Feb 17, 4:58 am, Thomas 'PointedEars' Lahn <PointedE...@web.de> wrote: In Spidermonkey Functions absolutely do have a name:- var x = function y() { console.log(arguments.callee.name); }; x();
10
3864
by: Frank O'Hara | last post by:
Hello everyone, I'm just learning some of the depth that Javascript has to offer. I have to say that it is quite amazing. Anyway, I'm translating some of my older, classical code to try to take advantage of some of the new things I'm learning but I'm a little stuck with this one (see snip): <snip> document.getElementById("button1").blink...
0
7794
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7710
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
8040
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
1
7800
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
8092
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
6437
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
1
5610
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
3745
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
1051
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.