overload builtin operator

Robert Kern rkern at ucsd.edu
Thu Aug 25 05:12:33 EDT 2005


Shaun wrote:
> Hi,
> 
> I'm trying to overload the divide operator in python for basic arithmetic.
> eg. 10/2 ... no classes involved.
> 
> I am attempting to redefine operator.__div__ as follows:
> 
>      # my divide function
>      def safediv(a,b):
>          return ...
> 
>      # reassign buildin __div__
>      import operator
>      operator.__div__ = safediv
> 
> The operator.__dict__ seems to be updated OK but the '/' operator still  
> calls buildin __div__

Actually,

  int1 / int2

is, I believe, equivalent to

  int.__div__(int1, int2)

operator.__div__ does not get called.

> Does anyone know if this is possible and if I'm going along the correct  
> path with my attempts above?
> Is it possible to do this using a C extention?

No, you can't replace the methods on builtin types.

-- 
Robert Kern
rkern at ucsd.edu

"In the fields of hell where the grass grows high
 Are the graves of dreams allowed to die."
  -- Richard Harter




More information about the Python-list mailing list