473,387 Members | 1,535 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

Parameterized Functions without Classes

Hi Pythonistas,

just as a small comment on the side-effects of the
rather new concept of local functions with access to
their scope:

This concept can be used to avoid having extra
classes just for keeping some read-only state.

Since this feature is not so obvious in the first
place, I thought to share the obervation.

In the ancient times, I saw myself writing classes
to parameterize functions, like this:

class Converter:
def __init__(self, scale):
self.scale = scale
def __call__(self, arg):
return self.scale * arg

inch_to_cm = Converter(2.54)
cm_to_inch = Converter(1 / 2.54)
....
inch_to_cm(20) 50.799999999999997 cm_to_inch(20) 7.8740157480314954
This can be easily done without an extra class, just by
local variables which access the outer scope:

def _converter(scale):
def convert(arg):
return scale * arg
return convert

inch_to_cm = _converter(2.54)
cm_to_inch = _converter(1 / 2.54)
inch_to_cm(20) 50.799999999999997 cm_to_inch(20) 7.8740157480314954


This trick (and I don't consider it a trick) works for
all cases, where you don't need write access to an instance
variable, but read access, only.
It is a very clean way to parameterize functions, and it
is very effective since there is no attribute lookup
necessary.

cheers - chris

--
Christian Tismer :^) <mailto:ti****@stackless.com>
Mission Impossible 5oftware : Have a break! Take a ride on Python's
Johannes-Niemeyer-Weg 9a : *Starship* http://starship.python.net/
14109 Berlin : PGP key -> http://wwwkeys.pgp.net/
work +49 30 89 09 53 34 home +49 30 802 86 56 mobile +49 173 24 18 776
PGP 0x57F3BF04 9064 F4E1 D754 C2FF 1619 305B C09C 5A3B 57F3 BF04
whom do you want to sponsor today? http://www.stackless.com/
Jul 18 '05 #1
8 1478
Christian Tismer <ti****@stackless.com> wrote:
just as a small comment on the side-effects of the
rather new concept of local functions with access to
their scope:
[...]
def _converter(scale):
def convert(arg):
return scale * arg
return convert


In what way is that different from using an ordinary lambda
function? i.e.:

def _converter(scale):
return lambda arg: scale * arg

Of course, the use of lambda functions is very limited
because (unfortunately) they can contain only one single
expression. But other than that, it's pretty much the
same concept, isn't it?

Best regards
Oliver

--
Oliver Fromme, Konrad-Celtis-Str. 72, 81369 Munich, Germany

``All that we see or seem is just a dream within a dream.''
(E. A. Poe)
Jul 18 '05 #2
Oliver Fromme wrote:
Christian Tismer <ti****@stackless.com> wrote:
> just as a small comment on the side-effects of the
> rather new concept of local functions with access to
> their scope:
> [...]
> def _converter(scale):
> def convert(arg):
> return scale * arg
> return convert
In what way is that different from using an ordinary lambda
function? i.e.:


There is no difference than the existing differences
between lambdas and def'ed functions.
The scope rules are the same.
Of course, the use of lambda functions is very limited
because (unfortunately) they can contain only one single
expression. But other than that, it's pretty much the
same concept, isn't it?


Lambdas were not the topic, since they are a deprecated
feature, but sure it works.
The intent of my post was to show a "clean" way to do
things classless, directed to newcomers.
It was not about showing all possible (and unrecommended)
ways to do it. That would have filled 5 pages :-)

ciao - chris

--
Christian Tismer :^) <mailto:ti****@stackless.com>
Mission Impossible 5oftware : Have a break! Take a ride on Python's
Johannes-Niemeyer-Weg 9a : *Starship* http://starship.python.net/
14109 Berlin : PGP key -> http://wwwkeys.pgp.net/
work +49 30 89 09 53 34 home +49 30 802 86 56 mobile +49 173 24 18 776
PGP 0x57F3BF04 9064 F4E1 D754 C2FF 1619 305B C09C 5A3B 57F3 BF04
whom do you want to sponsor today? http://www.stackless.com/

Jul 18 '05 #3
On Fri, 25 Jun 2004, Christian Tismer wrote:
Lambdas were not the topic, since they are a deprecated
feature, but sure it works.


Since when are lambdas deprecated? And if so, why?

IMHO, the best way to parameterize functions is with 2.4's proposed
partial() function:

def converter(factor,val):
return val*factor

inchtocm=partial(converter,2.54)
cmtoinch=partial(converter,1/2.54)

where a handy pre-2.4 definition of partial is:

def partial(func,*args,**kw):
return lambda *a,**k: func(*(args+a),**dict(kw.items()+k.items()))

Jul 18 '05 #4
Christopher T King wrote:
On Fri, 25 Jun 2004, Christian Tismer wrote:
Lambdas were not the topic, since they are a deprecated
feature, but sure it works.


Since when are lambdas deprecated? And if so, why?

IMHO, the best way to parameterize functions is with 2.4's proposed
partial() function:

def converter(factor,val):
return val*factor

inchtocm=partial(converter,2.54)
cmtoinch=partial(converter,1/2.54)

where a handy pre-2.4 definition of partial is:

def partial(func,*args,**kw):
return lambda *a,**k: func(*(args+a),**dict(kw.items()+k.items()))


In what way is that different from using an ordinary function?

def partial(func, *args, **kw):
def call(*a, **k):
return func(*(args+a), **dict(kw.items()+k.items()))
return call

Of course, the use of functions is not limited like lambdas
because (fortunately) they can contain more than one single
expression. But other than that, it's pretty much the
same concept, isn't it?

:-)

My-newsreader-doesn't-support-circular-threads-yetly yours,
Peter
Jul 18 '05 #5
Christopher T King wrote:
On Fri, 25 Jun 2004, Christian Tismer wrote:

Lambdas were not the topic, since they are a deprecated
feature, but sure it works.

Since when are lambdas deprecated? And if so, why?


Not really deprecated, but Python is trying to replace
it since a longer time. PEP 290, for instance.
IMHO, the best way to parameterize functions is with 2.4's proposed
partial() function:


My intent was to show a nice thing that can be done today,
not a contest which alternatives are there, including
unreleased features.
And lambda is nothing than a function with restricted syntax,
so why do we burn bandwidth off-topic.
--
Christian Tismer :^) <mailto:ti****@stackless.com>
Mission Impossible 5oftware : Have a break! Take a ride on Python's
Johannes-Niemeyer-Weg 9a : *Starship* http://starship.python.net/
14109 Berlin : PGP key -> http://wwwkeys.pgp.net/
work +49 30 89 09 53 34 home +49 30 802 86 56 mobile +49 173 24 18 776
PGP 0x57F3BF04 9064 F4E1 D754 C2FF 1619 305B C09C 5A3B 57F3 BF04
whom do you want to sponsor today? http://www.stackless.com/
Jul 18 '05 #6
Christian Tismer <ti****@stackless.com> wrote:
just as a small comment on the side-effects of the
rather new concept of local functions with access to
their scope:


Why is it "new concept"? Sure, nested scope is not ancient stuff, but
it's been out for a while. I don't think other people would call it
"new".

I have counted 7 messages in the thread, so far. How come no one
mentioned the keyword "closure"?

Just wondering. Because searching the Python newsgroup with keyword
"closure" turns up many previous threads on this subject.

regards,

Hung Jung
Jul 18 '05 #7
On Fri, 25 Jun 2004, Peter Otten wrote:
Christopher T King wrote:
def partial(func,*args,**kw):
return lambda *a,**k: func(*(args+a),**dict(kw.items()+k.items()))


In what way is that different from using an ordinary function?
def partial(func, *args, **kw):
def call(*a, **k):
return func(*(args+a), **dict(kw.items()+k.items()))
return call


It's not, other than that mine is shorter and less readable :P

My point of demonstrating the use of partial() though (this is in response
to Christian also) is that along with 2.4 functions such as itemgetter()
and attrgetter() and list/generator comprehensions, it will help remove
the need for nearly all uses of lambda functions or their equivalent
nested functions.

Jul 18 '05 #8
Jacek Generowicz <ja**************@cern.ch> wrote:
hu********@yahoo.com (Hung Jung Lu) writes:
I have counted 7 messages in the thread, so far. How come no one
mentioned the keyword "closure"?


I was tempted, but realized that this would only lead to me producing
a combination of my 3 favourite c.l.py rants, so I refrained.


How about a codeblock-based language that does the following:

f = function( args={x;y;z=g(5);}, deco={synchronized;},
init={.static=1;}, code={

w = x+y+z+.static;
.static += 1;
w;

});

f(1,2,3) # returns 7
f(1,2,3) # returns 8

(a) "args" codeblock is executed in such a way that each additional
name is used to build up the argument list of the function. (Special
setattr()/setslot() function is used, if you know what I mean.)

(b) "deco" codeblock builds up names to be used for special decorated
features.

(c) "init" codeblock is run only the first time the function is
invoked.

(d) "code" is the regular codeblock of the function. The return value
is the value of the codeblock, which is the value of the last
expression.

(f) functions are self-aware. The "self" name is optional: an initial
dot suffices. This is enough to take of closure needs, I think.

(g) functions are built by using the "function" function. Don't ask me
chicken-and-egg questions.

regards,

Hung Jung
Jul 18 '05 #9

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

Similar topics

18
by: vrillusions | last post by:
I've been using functions since I first started using php, but I've been hearing more and more about classes, which I never really looked at that much. I understand the whole OO programming...
12
by: bissatch | last post by:
Hi, Generally if I re-use code, I use a function. If I need to use these functions over a number of pages I write the function to an include file where all pages have access. So when should I...
99
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...
0
by: Anthony Baxter | last post by:
To go along with the 2.4a3 release, here's an updated version of the decorator PEP. It describes the state of decorators as they are in 2.4a3. PEP: 318 Title: Decorators for Functions and...
2
by: Bryan Olson | last post by:
The current Python standard library provides two cryptographic hash functions: MD5 and SHA-1 . The authors of MD5 originally stated: It is conjectured that it is computationally infeasible to...
30
by: Will Pittenger | last post by:
Does C# inline functions? I do not see a inline keyword. Is there an implicit inline? Can the compiler select functions for auto-inlining? I am more used to C++ where all these things are...
2
by: Bob Rock | last post by:
Hello, in the last few days I've made my first few attempts at creating mixed C++ managed-unmanaged assemblies and looking afterwards with ILDASM at what is visible in those assemblies from a...
10
by: Sean Dockery | last post by:
I have the following HTML file that I've been using for testing... <html> <head> <script type="text/javascript"> <!-- function handleWindowLoad() { var items = ; for (var i = 0; i < 11; i++)...
13
by: Simon Dean | last post by:
Hi, I have a couple of questions. If you don't mind. Sorry, I do get a bit wordy at times. First one just throws some thoughts around hoping for answers :-) 1) Anyone got a theory on the...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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,...
0
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,...

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.