473,785 Members | 2,209 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Creating anonymous functions using eval

I've been playing with a function that creates an anonymous function by
compiling a string parameter, and it seems to work pretty well:

def fn( text):
exec 'def foo' + text.strip()
return foo

This can be used like:

def foo( x):
print x( 2, 5)

foo( fn( '''
( x, y):
print 'x^2 + y^2 = ', x*x + y*y
return y
'''))

- which outputs:

x^2 + y^2 = 29
5
You can also mimic conventional function definitions:

f = fn( '''
( x, y):
print 'x, y=', x, y
print 1.0*x/y
return y
''')

print 'calling f'
f( 5, 6)

This outputs:

calling f
x, y= 5 6
0.833333333333
You do things like allow/require an initial `def' for clarity, check that all
the lines of text are indented so that nothing is executed when the anonymous
function is created, etc etc.

Obvious disadvantages are that the function text may have to escape quotes,
and will not be showed with syntax colouring in editors.

Apart from that, it seems quite a useful way of overcoming the limitations of
python's lambda.

But... I haven't seen this technique mentioned anywhere, so does anyone know
of any problems that I should be wary of?

- Julian

--
http://www.op59.net/
Jul 21 '05 #1
10 2403
How is this different from a nested function?

Jul 21 '05 #2
On Tue, 12 Jul 2005 08:28:45 -0700, Devan L wrote:
How is this different from a nested function?


Well, "this" is a newsgroup posting written by you. Nested functions in
Python are callable objects that exist as attributes of other callable
objects, so the two are very different.

Alternatively, if you expect a sensible answer, how about asking a
sensible question? You can start by telling us just what it is that you
are comparing to nested functions.

--
Steven.

Jul 21 '05 #3
Well, the string that gets passed is more or less a function
definition, which is then called with exec. I don't see why you'd need
to write a string out with the function definition and then call it.
You could just write the function.

As for the nested functions, I had been presuming that it was intended
to use as a better function than lambda within a function. Sorry for
the confusion.

Jul 21 '05 #4
Devan L wrote:
Well, the string that gets passed is more or less a function
definition, which is then called with exec. I don't see why you'd need
to write a string out with the function definition and then call it.
You could just write the function.

As for the nested functions, I had been presuming that it was intended
to use as a better function than lambda within a function. Sorry for
the confusion.


You missed Steven's point which is to quote the message to which you are
replying. Not everyone is reading this list in a conveniently threaded
form, so you need to provide some context for them to be able to follow
along.

--
Robert Kern
rk***@ucsd.edu

"In the fields of hell where the grass grows high
Are the graves of dreams allowed to die."
-- Richard Harter

Jul 21 '05 #5
> You missed Steven's point which is to quote the message to which you are
replying. Not everyone is reading this list in a conveniently threaded
form, so you need to provide some context for them to be able to follow
along.


Ah, sorry, I didn't quite get what he was referring to.

Jul 21 '05 #6
Robert Kern wrote:
Not everyone is reading this list in a conveniently threaded
form

Why not? Just about every modern newsgroup reader and e-mail app has a
threaded view option.
Jul 21 '05 #7
Joseph Garvin wrote:
Robert Kern wrote:
Not everyone is reading this list in a conveniently threaded form

Why not? Just about every modern newsgroup reader and e-mail app has a
threaded view option.


My newsreader supports threading, but the first message I see in this
thread is from Devan L. I didn't notice the "Re:" and assumed his post
was half in the subject line and half in the body.

Sometimes I only download the 100 most recent posts, so I don't see the
original (or referred-to) post. Other times the threading doesn't work
properly, splitting conversations or using the wrong level of
indentation. Also, this is both a newsgroup and a mailing list, and that
has adverse effects on threading as well.

So, please quote. =)

Dave
Jul 21 '05 #8
Joseph Garvin wrote:
Robert Kern wrote:
Not everyone is reading this list in a conveniently threaded
form


Why not? Just about every modern newsgroup reader and e-mail app has a
threaded view option.


Good point. Allow me to modify my statement: not all newsreaders/email
apps thread python-list/c.l.py conversations properly. The gateway often
messes things up.

It's also a royal pain in the butt to have to go read another message
just to dereference anaphora, threading or no.

--
Robert Kern
rk***@ucsd.edu

"In the fields of hell where the grass grows high
Are the graves of dreams allowed to die."
-- Richard Harter

Jul 21 '05 #9
On Tue, 12 Jul 2005 17:17:46 -0600, Joseph Garvin wrote:
Robert Kern wrote:
Not everyone is reading this list in a conveniently threaded
form

Why not? Just about every modern newsgroup reader and e-mail app has a
threaded view option.


Technology as a substitute for manners is it?

I have a modern newsgroup reader. I don't like threaded views, but even
if I did, that's not the point. News servers sometimes drop posts, or the
posts expire. Sometimes news readers lose posts (that just happened to me
yesterday). Sometimes threading breaks. Quoting enough of the previous
post to establish context is the only sensible behaviour in the face of
all these potential problems.

But even that is not the point.

It is rude for people to assume that their post is so vitally important to
me that I'll drop what I'm doing to hunt back through past posts searching
for context. Even if that search is "back one post in the thread", that's
still one post too many.

In the face of that breach of manners, people may choose to respond in
many ways. Some might choose to reward the rudeness by searching previous
posts, then responding with an answer to the question. Some might choose
to just ignore the post, which has the disadvantage of leaving the
original poster no wiser and likely to repeat his behaviour. Some might
flame them, which is usually counterproducti ve. And some might drop some
fairly heavy hints, but that assumes the poster is capable of getting a
clue.
--
Steven.

Jul 21 '05 #10

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

Similar topics

0
1174
by: Andrew Collier | last post by:
Hello, I was writing a program which used some nested functions, and came across a behaviour which I was unable to explain. I can summarise it with the example below: #!/usr/bin/env python
2
2484
by: Salvatore | last post by:
Hello, Given an expression f = '2*x+3' from a user input I would like to do some sort of function userFunction(x): return f(x) is it possible with Javascript ?
20
3125
by: svend | last post by:
I'm messing with some code here... Lets say I have this array: a1 = ; And I apply slice(0) on it, to create a copy: a2 = a1.slice(0); But this isn't a true copy. If I go a1 = 42, and then alert(a2) I will see 42 there too. I'm doubting, but I was
8
2559
by: lawrence | last post by:
I'm learning Javascript. I downloaded a script for study. Please tell me how the variable "loop" can have scope in the first function when it is altered in the second function? It is not defined in global space, therefore it is not a global variable, yes? Even if it was global, how would it get from one function to another? In PHP variables are copied by value. Are they copied by reference in Javascript? <SCRIPT LANGUAGE="JavaScript">
0
1126
by: Andrew Westgarth | last post by:
Hi all, i'm struggling with a page idea I have. I need to write a page with an A to Z list of available schools in the area. I only want to display the letters in the A to Z which have school information under them, i.e. A,b,c,d,f if no schools beginning with e are available. My chosen page layout out would be
60
5468
by: jacob navia | last post by:
Gnu C features some interesting extensions, among others compound statements that return a value. For instance: ({ int y = foo(); int z; if (y>0) z = y; else z=-y; z; }) A block enclosed by braces can appear within parentheses to form a block that "returns" a value. This is handy in some macros, or in other applications.
11
7175
by: breal | last post by:
I have three lists... for instance a = ; b = ; c = ; I want to take those and end up with all of the combinations they create like the following lists
4
2130
by: Danny Shevitz | last post by:
Simple question here: I have a multiline string representing the body of a function. I have control over the string, so I can use either of the following: str = ''' print state return True '''
9
1876
by: Dahak | last post by:
I'm trying to generate dynamic functions to use as separate callbacks for an AJAX API call. The API doesn't seem to allow for the inclusion of any parameters in the callback, so I can't associate the call with the handling routine (for reference purposes, I'm calling the Google Language Translation API). As a work-around, I thought I'd dynamically generate a unique callback function for each API call. Right now, I'm stuck hobbling...
0
9646
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 usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9483
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 synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10346
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. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9956
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 choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8982
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 launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6742
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5514
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4055
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2887
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 effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.