[Python-3000] Use case for generics

Edward Loper edloper at gradient.cis.upenn.edu
Sun May 14 01:05:38 CEST 2006


Talin wrote:
> One way of thinking about generic functions is that they are the dynamic 
> languages' equivalent to C++ function overloading. Now, there are lots 
> of valid (and some not-so-valid) use cases for function overloading; I'm 
> just going to pick one of the most common ones.
> 
> Many GUI libraries have the concept of a "Rectangle" class which 
> represents the area of a widget. Typically, a rectangle can be 
> constructed in several ways: [...]

For this use case, I don't think that a direct translation of the 
overloaded-constructor design for C++ carries over into Python as a good 
design.  In particular, I think this would be better coded in Python 
using either keyword arguments, or factory methods.  I.e., I'd rather 
see the interface be either:

class Rectangle:
     def __init__(self, top=None, left=None, topleft=None, bottom=None,
                  right=None, bottomright=None, width=None, height=None):
         """
         Construct a new rectangle with the given dimensions.  All
         arguments should be specified as keyword arguments.

         @raise ValueError: If the given arguments do not provide enough
             information to define the rectangle; or if they contain
             conflicting information.
         """
         ...

Or:

class Rectangle:
     def __init__(self, x, y, w, h): ...

     @classmethod
     def from_pos_size(self, pos, size): ...

     @classmethod
     from ul_lr(self, ulpos, lrpos): ...

(Note, this is not an argument against generic functions, which I think 
definitely have their uses; just an argument that this isn't a use case 
where I would choose to use them.)

-Edward


More information about the Python-3000 mailing list