Hi Frans,
Since Python doesn't have static typing, how is the same result as traditional function overloads results in acheived?
With dynamic typing obviously. :-)
You can not reproduce the C++ overload idiom but you can get something close with manual type testing.
> To in a > function do an if statement with the type() function?
I am not aware of any other method.
def a( arg1 ): if type(arg1) == types.IntType: return aWithInt(arg1) if type(arg1) == types.ListType: return aWithList(arg1) ...
As you see, it is a bit tedious sometimes.
If you want to juggle with completely different signatures, you have to play with variable argument lists. But I have found in my experience that the best way to get close to the C++ idiom, while improving readbility, is by using kwparams:
def a(**kwparams): if kwparams.has_key('argInt'): aWithInt(kwparams['argInt']) if kwparams.has_key('argString'): aWithString(kwparams['argString'])
The parsing code is the same, but the intent of the user is better expressed and you can catch misuse in a better fashion:
if kwparams.has_key('argInt') and kwparams.has_key('argString'):
print "You stupid moron, a can be used only with string or int but not both at the same time!"
sys.exit(1)
The example speaks better in a real case. Imagine a processPixmap function: processPixmap( pixmap=QPixmap(...) ) processPixmap( filename='my_pixmap.png' ) processPixmap( buffer=my_pixmap_string_content )
It works actually even better with multiple arguments.
regards,
Philippe -- http://mail.python.org/mailman/listinfo/python-list