473,659 Members | 2,662 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 1444
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 NotImplementedE rror('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 "parameteri zed" 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********@pan afonet.grwrote in message
news:11******** *************@k 79g2000hse.goog legroups.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 NotImplementedE rror('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 NotImplementedE rror('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
3762
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:...
44
2402
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 statement: void print_structs(void * struct_argument, enum struct_type stype) { switch(stype) { case STRUCT_TYPE_1:
23
3992
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 who will find them very helpfull. gcc has them as a non-standard option, but only when compiling C language code, so I'm afraid there might be some obscure reason why local functions are not so easy to be dealt with in C++, which I do not yet know.
10
2065
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 = document.createElement('div'); elt.innerHTML = "" + i;
4
1576
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 discussed was: function object(o) { function F() {} F.prototype = o; return new F();
2
3881
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
2480
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 unique ID which tells me the name of the PHP file for the widget. Each widget should be able to access its PHP file with GET and POST methods, and to re-draw its innerHTML on response. I am using a simple Ajax library called XHConn...
18
2479
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 Tommy Nordgren tommy.nordgren@comhem.se
9
1867
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
8427
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
8330
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
8746
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
8523
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
8626
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
4334
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2749
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
1975
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1737
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.