474,029 Members | 42,677 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How do I dynamically create functions without lambda?

I want my code to be Python 3000 compliant, and hear
that lambda is being eliminated. The problem is that I
want to partially bind an existing function with a value
"foo" that isn't known until run-time:

someobject.newf unc = lambda x: f(foo, x)

The reason a nested function doesn't work for this is
that it is, well, dynamic. I don't know how many times
or with what foo's this will be done.

Now, I am sure there are a half-dozen ways to do this.
I just want the one, new and shiny, Pythonic way. ;-)

Jan 27 '06
25 2608
Steven D'Aprano wrote:
On Fri, 27 Jan 2006 11:41:56 -0800, Kay Schluehr wrote:

Russell wrote:
I want my code to be Python 3000 compliant, and hear
that lambda is being eliminated. The problem is that I
want to partially bind an existing function with a value
"foo" that isn't known until run-time:

someobject.newf unc = lambda x: f(foo, x)

The reason a nested function doesn't work for this is
that it is, well, dynamic. I don't know how many times
or with what foo's this will be done.

Now, I am sure there are a half-dozen ways to do this.
I just want the one, new and shiny, Pythonic way. ;-)
If you want to code partial application without lambda I recommend
using the code presented in the accepted PEP 309 that will be
implemented in the functional module in Python 2.5.

http://www.python.org/peps/pep-0309.html

Fascinating. A couple of thoughts:

- I really wish that people would make up their minds about what currying
is, and how it differs from partials and closures. If the people who
do know can't agree, how do they expect the rest of us to understand?


If they can't agree they probably don't know ;)

Concepts like "closure" and "currying" are well defined in lambda
calculus and hence in functional programming.
- What, if anything, is the difference between a closure and an iterator?
Is an iterator just a closure wrapped up with an API?


I would expect a closure to be a function with free/unbound variables
that are bound by an enclosing context. In FP slang a function without
any free variables is called a "combinator ". An iterator is a function
related to an abstract data type equipped with a partial order. The
iterator abstracts from the particular ordering scheme and makes the
ADT look like a list. In Python we have a nice correspondence between
generators as implicit defined sequences of yielded values, iterators
that enable uniform access to the values produced by generators and
lists that make the sequence explicit ( if finite ).

Fun with combinators
=============== =======
There are quite interesting relationships deep down in the theory of
computation. For instance understanding recursion in lambda calculus is
not that easy because you cannot simply reintroduce an anonymous
function by the name into its own body. The idea is to create a
fixpoint of a higher order curried function instead. See for example
this curried extension of a factorial:

F = lambda h: lambda n : n<2 and 1 or n*h(n-1)

Now imagine you have a fixpoint fix(F) of F which is again a function
and pass it into F then you will get:

fix(F) = F(fix(F)) = lambda n : n<2 and 1 or n*fix(F)(n-1)

That is fix(F) is actually the searched factorial ! There is a generic
way to create fixpoints of higher order curried functions such as F.
The most popular one is the so called Y-combinator ( not to confuse
with Paul Grahams company ;).

In Python you can write:

Y = lambda g: (lambda f: g(lambda arg: f(f)(arg))) (lambda f: g(lambda
arg: f(f)(arg)))

This serves the purpose. Try Y(F) and see.

Kay

Jan 28 '06 #11
On Sat, 28 Jan 2006 00:13:28 -0800, Kay Schluehr wrote:

[snip lambda calculus stuff]
In Python you can write:

Y = lambda g: (lambda f: g(lambda arg: f(f)(arg))) (lambda f: g(lambda
arg: f(f)(arg)))

This serves the purpose. Try Y(F) and see.

Is any of this stuff maintainable in the real world of IT, where
most programmers don't have computer science degrees? You come along six
months after the project was finished to maintain this code and discover
that the whiz-kid lambda calculus guy never commented anything because
that would detract from the elegance of his one liners; what happens next?

--
Steven.

Jan 28 '06 #12
Steven D'Aprano wrote:
On Sat, 28 Jan 2006 00:13:28 -0800, Kay Schluehr wrote:

[snip lambda calculus stuff]
In Python you can write:

Y = lambda g: (lambda f: g(lambda arg: f(f)(arg))) (lambda f: g(lambda
arg: f(f)(arg)))

This serves the purpose. Try Y(F) and see.

Is any of this stuff maintainable in the real world of IT, where
most programmers don't have computer science degrees?


Probably not. But the good thing about Y is that it is in closed form
and the expression is not infinitely long. By the way I have no less a
hard time to read C code with advanced data-structures and many type
casts which is much more likely to happen in the "real world".
From what I've seen the only *practical* purpose fixpoint combinators serve is a kind of recursion "overloadin g". Without modifying F one can
memoize values by adapting the fixpoint combinator. We already know
something similar from the Go4 "command pattern" but there is no
self-referential entanglement and it is less general.
You come along six
months after the project was finished to maintain this code and discover
that the whiz-kid lambda calculus guy never commented anything because
that would detract from the elegance of his one liners; what happens next?


Ask a Scheme guy at LtU. Accuse the original author in Den Haag and if
caught put him to shame by making photos at a dentist. Google for
"lambda calculus Y". Ask someone here at comp.lang.pytho n. Ask your
boss for more time ;)

Kay

Jan 28 '06 #13
Op 2006-01-27, Russell schreef <ru************ @hotmail.com>:
I want my code to be Python 3000 compliant, and hear
that lambda is being eliminated. The problem is that I
want to partially bind an existing function with a value
"foo" that isn't known until run-time:

someobject.newf unc = lambda x: f(foo, x)

The reason a nested function doesn't work for this is
that it is, well, dynamic. I don't know how many times
or with what foo's this will be done.
I don't see how dynamic is supposed to contradict with
nested functions. I assume from your tekst that foo
has some parameter-like charateristics. So the following
should work.

def produce(foo):

def func(x):
return f(foo, x)

return func
someobject.newf unc = produce(foo)
This kind of code can be generalized. Look for partial
application or curry.

Now, I am sure there are a half-dozen ways to do this.
I just want the one, new and shiny, Pythonic way. ;-)


The new and shiny, pythonic way depends on what you
really want, your question was a bit vague to answer
that.

--
Antoon pardon
Jan 30 '06 #14
In article <pa************ *************** *@REMOVETHIScyb er.com.au>,
Steven D'Aprano <st***@REMOVETH IScyber.com.au> wrote:
On Sat, 28 Jan 2006 00:13:28 -0800, Kay Schluehr wrote:

[snip lambda calculus stuff]
In Python you can write:

Y = lambda g: (lambda f: g(lambda arg: f(f)(arg))) (lambda f: g(lambda
arg: f(f)(arg)))

This serves the purpose. Try Y(F) and see.

Is any of this stuff maintainable in the real world of IT, where
most programmers don't have computer science degrees? You come along six
months after the project was finished to maintain this code and discover
that the whiz-kid lambda calculus guy never commented anything because
that would detract from the elegance of his one liners; what happens next?


Excessive cleverness can lead to unmaintainable code. So can excessive stupidity.
Since there are a lot more stupid people than clever people out there I think
the more likely scenario is having to maintain unmaintainable code written by a
complete idiot whose programming knowledge comes solely from books whose titles
end with "In 7 Days".

Oh, and I'd hope that code reviews, etc. would have kept lambda-boy from getting
too far down this path of self invocation.

Alan
--
Defendit numerus
Feb 1 '06 #15
Alan Morgan <am*****@xenon. Stanford.EDU> wrote:
...
Excessive cleverness can lead to unmaintainable code. So can excessive
stupidity.
+1 QOTW.
Since there are a lot more stupid people than clever people out there I
think the more likely scenario is having to maintain unmaintainable code
written by a complete idiot whose programming knowledge comes solely from
books whose titles end with "In 7 Days".


Disagree -- far more people THINK they're clever, than really ARE
clever. According to a recent article in the Financial Times, over 40%
of a typical financial firm's employees firmly believe they are among
the 5% best employees of the firm -- and the situation, believe me, is
no different in programming.
Alex
Feb 2 '06 #16
Alex Martelli wrote:
Alan Morgan <am*****@xenon. Stanford.EDU> wrote:
...
Excessive cleverness can lead to unmaintainable code. So can excessive
stupidity.

+1 QOTW.

++
Since there are a lot more stupid people than clever people out there I
think the more likely scenario is having to maintain unmaintainable code
written by a complete idiot whose programming knowledge comes solely from
books whose titles end with "In 7 Days".

Disagree -- far more people THINK they're clever, than really ARE
clever. According to a recent article in the Financial Times, over 40%
of a typical financial firm's employees firmly believe they are among
the 5% best employees of the firm -- and the situation, believe me, is
no different in programming.


Just as 85% of drivers believe their skill level is "above average".

regards
Steve
--
Steve Holden +44 150 684 7255 +1 800 494 3119
Holden Web LLC www.holdenweb.com
PyCon TX 2006 www.python.org/pycon/

Feb 2 '06 #17
In article <1h************ *************** *@yahoo.com>,
Alex Martelli <al*****@yahoo. com> wrote:
Alan Morgan <am*****@xenon. Stanford.EDU> wrote:
...
Excessive cleverness can lead to unmaintainable code. So can excessive
stupidity.
+1 QOTW.


import blush
Since there are a lot more stupid people than clever people out there I
think the more likely scenario is having to maintain unmaintainable code
written by a complete idiot whose programming knowledge comes solely from
books whose titles end with "In 7 Days".


Disagree -- far more people THINK they're clever, than really ARE
clever.


No doubt about it, but I don't see how it contradicts my statement.
According to a recent article in the Financial Times, over 40%
of a typical financial firm's employees firmly believe they are among
the 5% best employees of the firm -- and the situation, believe me, is
no different in programming.


I wonder if python, which has a low barrier to entry due to its simple syntax
and general readability, might not have a worse time of this than other languages.

Alan
--
Defendit numerus
Feb 2 '06 #18
Alex Martelli wrote:
Disagree -- far more people THINK they're clever, than really ARE
clever. According to a recent article in the Financial Times, over 40%
of a typical financial firm's employees firmly believe they are among
the 5% best employees of the firm -- and the situation, believe me, is
no different in programming.


It's apparently no different anywhere:
http://www.phule.net/mirrors/unskilled-and-unaware.html
--
Benji York
Feb 2 '06 #19
Benji York <be***@benjiyor k.com> wrote:
Alex Martelli wrote:
Disagree -- far more people THINK they're clever, than really ARE
clever. According to a recent article in the Financial Times, over 40%
of a typical financial firm's employees firmly believe they are among
the 5% best employees of the firm -- and the situation, believe me, is
no different in programming.


It's apparently no different anywhere:
http://www.phule.net/mirrors/unskilled-and-unaware.html


Tx. Maybe it's a genetically adaptive trait: the FT points out that
while there is little correlation between an employee's opinion of their
skills, and the employee's actual performance, there IS positive
correlation between said opinion and the employee's career advancement.
One way to explain the correlation is: if you truly (albeit perhaps
mistakenly) believe you're great, you project that and are more likely
to get promotions or raises, than is somebody else, perhaps objectively
better, who's torn by self-doubt and projects THAT.

My working hypothesis would be that this effect would be far stronger in
fields where it's hard to get hard quantitative measures of performance,
so the managers (or clients, etc) rely to a large extent on subjective
judgment which can be influenced by such "projections".. .
Alex

Feb 3 '06 #20

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

Similar topics

99
6059
by: David MacQuigg | last post by:
I'm not getting any feedback on the most important benefit in my proposed "Ideas for Python 3" thread - the unification of methods and functions. Perhaps it was buried among too many other less important changes, so in this thread I would like to focus on that issue alone. I have edited the Proposed Syntax example below to take out the changes unecessary to this discussion. I left in the change of "instance variable" syntax (...
53
3750
by: Oliver Fromme | last post by:
Hi, I'm trying to write a Python function that parses an expression and builds a function tree from it (recursively). During parsing, lambda functions for the the terms and sub-expressions are constructed on the fly. Now my problem is lazy evaluation. Or at least I think it is. :-)
76
3885
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 recent c.l.p discussion:...
37
2236
by: Kay Schluehr | last post by:
Since George Sakkis proposed a new way of doing list comprehensions http://groups-beta.google.com/group/comp.lang.python/browse_frm/thread/ac5023ad18b2835f/d3ff1b81fa70c8a7#d3ff1b81fa70c8a7 letting tuples-like objects (x,y,z=0) acting as functions on other tuples I wonder why this would not be a good starting point of rethinking anonymus functions? In Georges proposition the action is
4
2383
by: Max Derkachev | last post by:
Good day to all. Some time ago I'd been playing with a framework which uses dynamic class creation havily. Say, I could do: class A: pass # I method name is dynamic meth_name = 'foo'
8
4845
by: Falc2199 | last post by:
Hi, Does anyone know how to make this work? var sectionId = 5; repeat_section_sectionId(); function repeat_section_5(){ alert("firing"); }
13
4409
by: invincible | last post by:
hi friends , how can I declare / create function during runtime similiar to lambda in lisp. thanks Mohan
11
3948
by: Josiah Manson | last post by:
In the following program I am trying to learn how to use functional programming aspects of python, but the following program will crash, claiming that the recursion depth is too great. I am attempting to make a list of polynomial functions such that poly(3) = 1, poly(3) = 3, poly(3) = 9, etc. Could someone point me in the right direction? Thanks. def make_polys(n): """Make a list of polynomial functions up to order n. """
5
1960
by: Maxim Veksler | last post by:
Hello, I'm new on this list and in python. It seems python has some interesting concept of "ad hoc" function which I'm trying to understand without much success. Take the following code for example: """ .... return lambda x: x + n
0
10512
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
10313
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
11580
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
11932
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 most users, this new feature is actually very convenient. If you want to control the update process,...
0
10270
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
6785
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
5367
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
2
4911
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3936
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.