473,388 Members | 1,480 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,388 software developers and data experts.

Replacing overloaded functions with closures.

Hi,

i am trying, to no avail yet, to take a C#'s overloaded functions
skeleton and rewrite it in Python by using closures.
I read somewhere on the net (http://dirtsimple.org/2004/12/python-is-
not-java.html) that in Python we can reduce code duplication for
overloaded functions by using closures.

I do not quite understand this. Let's say we have the following simple
C# code:

int func(int i) { return i * 2; }
string func(string s) { return s + s; }
bool func(bool f) { return !f; }

I wasn't able to find a way to express this thing in closures. I even
tried to have the parameters i, s and f as parameters with default
arguments with None value in the inner function and there to check for
the None and do the needed work but i am not sure if this is the
correct solution.

Any help ?
thanks in advance.

Jul 30 '07 #1
4 1433
The closures discussed in the article are not a solution for
function overloading. They are a solution for function
composition.
Hmmm....
>
Python generally has no need for function name overloading--if
you really want it you must do it manually using runtime type
checking.

def func(obj):
if isinstance(obj, bool):
return not obj
elif isinstance(obj, int):
return obj * 2
elif isinstance(obj, basestring):
return obj + obj
else:
raise NotImplementedError('type %r not supported' % type(obj))
I have already come up with that solution but i was a little excited
from that article that i can do the same thing with closures...And get
rid of the isinstance commands.

I'm not sure what the author was getting at, exactly.
May be that point confused me too!

Thanks Neil!

Jul 30 '07 #2
king kikapu a écrit :
Hi,

i am trying, to no avail yet, to take a C#'s overloaded functions
skeleton and rewrite it in Python by using closures.
I read somewhere on the net (http://dirtsimple.org/2004/12/python-is-
not-java.html) that in Python we can reduce code duplication for
overloaded functions by using closures.
Then you should re-read more carefully this article. While closures are
effectively a great way to reduce code duplication, they are by no mean
presented as a way to replace function overloading - or at least not
directly[1]. The idea presented here is to use closures to write
functions that will return "parameterized" functions, and (IMHE at
least) this is mostly useful in frameworks, ORMs and like.

[1] you may want to have a look at another work by the same author:
http://peak.telecommunity.com/DevCen...sitorRevisited
which introduces the RuleDispatch generic function package.

HTH
Jul 30 '07 #3

"king kikapu" <ab********@panafonet.grwrote in message
news:11*********************@k79g2000hse.googlegro ups.com...
| def func(obj):
| if isinstance(obj, bool):
| return not obj
| elif isinstance(obj, int):
| return obj * 2
| elif isinstance(obj, basestring):
| return obj + obj
| else:
| raise NotImplementedError('type %r not supported' % type(obj))
|
| I have already come up with that solution but
|...And get rid of the isinstance commands.

A sometimes alternative is a dict (untested):

func_switch = {
bool: lambda o: not o,
int: lambda i: i*2,
str: lambda s: s+s,
unicode: lambda s: s+s
}

def func(o):
try: return func_switch[type(o)]
except IndexError:
raise NotImplementedError('type %r not supported' % type(obj))

but this does not work for instances of subclasses the way isinstance does.

tjr


Jul 30 '07 #4
Ok, i see...

Thank you all :)

Jul 31 '07 #5

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

Similar topics

76
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,...
44
by: bahadir.balban | last post by:
Hi, What's the best way to implement an overloaded function in C? For instance if you want to have generic print function for various structures, my implementation would be with a case...
23
by: Timothy Madden | last post by:
Hello all. I program C++ since a lot of time now and I still don't know this simple thing: what's the problem with local functions so they are not part of C++ ? There surely are many people...
10
by: Emre Sevinc | last post by:
Take a look at the following snippet: <html> <head> <script> function add(elementId) { var container = document.getElementById(elementId); for (var i = 0; i < 10; i++) { var elt =...
4
by: Daniel | last post by:
Hi, I was reading Douglas Crockford's article on prototypal inheritance at http://javascript.crockford.com/prototypal.html. I think it also relates to a post back in Dec 2005. The mechanism...
2
by: desktop | last post by:
If a function should work with different types you normally overload it: void myfun(int a){ // do int stuff } void myfun(std::string str){ // do string stuff }
1
by: joe_doufu | last post by:
I'm creating a page with multiple "widgets", each with its own XMLHttpRequest object, so the user can play with the widgets in parallel. The widgets are enclosed in divs with class "widget" and a...
18
by: Tommy Nordgren | last post by:
Given the following: def outer(arg) avar = '' def inner1(arg2) # How can I set 'avar' here ? ------------------------------------- This sig is dedicated to the advancement of Nuclear Power...
9
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...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
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
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
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
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...
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.