[Python-3000] Use case for generics

Nick Coghlan ncoghlan at gmail.com
Sun May 14 03:22:33 CEST 2006


Edward Loper wrote:
> (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.)

Agreed - the use cases I see for function overloading in Python are more in 
the domain where the inputs to the function are conceptually "the same", but 
may require different handling due to implementation details.

The rectangle construction example doesn't quite fit into that category, as 
the different arguments are not conceptually the same.

However, where function overloading does come in is when you have a rectangle 
that looks something like Edward's:

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

      @classmethod
      @overloaded
      def from_pos_size(cls, pos, size):
          return cls(pos.x, pos.y, size.w, size.h)

      @classmethod
      @overloaded
      def from_ul_lr(cls, ulpos, lrpos): ...
          x = ulpos.x
          y = ulpos.y
          return cls(x, y, lrpos.x - x, lrpos.y - y)


This rectangle assumes that positions are given as x & y coordinates, and 
sizes are given by 'w' and 'h' attributes.

A simple overload would let you use a different size object that wrote out the 
attribute names in full:

@Rectangle.from_pos_size.overload
def Rectangle_from_pos_MySize(cls, pos, size : MySize):
     return cls(pos.x, pos.y, size.width, size.height)

Or you might use complex numbers for positions and sizes instead of special 
classes:

@Rectangle.from_pos_size.overload
def Rectangle_from_complex_pos_size(cls, pos : complex, size : complex):
     return cls(pos.real, pos.imag, size.real, size.imag)

@Rectangle.from_ul_lr.overload
def Rectangle_from_ul_lr(cls, ul : complex, lr : complex):
     size = lr - ul
     return cls(ul.real, ul.imag, size.real, size.imag)

Cheers,
Nick.

-- 
Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia
---------------------------------------------------------------
             http://www.boredomandlaziness.org


More information about the Python-3000 mailing list