Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8680973
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 12, 20262026-06-12T21:23:07+00:00 2026-06-12T21:23:07+00:00

I have an object from a library (numpy.ndarray), in which I’ve substituted the _

  • 0

I have an object from a library (numpy.ndarray), in which I’ve substituted the _iadd_ method for a custom one.
If I call object._iadd_(x), it works as expected. However, object+=x seems to call the old (unsubstituted) method.
I wanted to prevent overflows on numpy from occurring on specific cases, so I created a context manager for that. Here’s the (still very crude) code:

class NumpyOverflowPreventer( object ):
    inverse_operator= {'__iadd__':'__sub__', '__isub__':'__add__', '__imul__': '__div__', '__idiv__':'__mul__'}

    def _operate(self, b, forward_operator):
        assert type(b) in (int, float)
        reverse_operator= NumpyOverflowPreventer.inverse_operator[forward_operator]
        uro= getattr(self.upper_range, reverse_operator)
        lro= getattr(self.lower_range, reverse_operator)
        afo= self.originals[ forward_operator ]
        overflows= self.matrix > uro( b )
        underflows= self.matrix < lro( b )
        afo( b )
        self.matrix[overflows]= self.upper_range
        self.matrix[underflows]= self.lower_range
        
    def __init__(self, matrix):
        m= matrix
        assert m.dtype==np.uint8
        self.matrix= m
        self.lower_range= float(0)
        self.upper_range= float(2**8-1)
        
    def __enter__(self):
        import functools
        self.originals={}
        for op in NumpyOverflowPreventer.inverse_operator.keys():
            self.originals[ op ] = getattr( self.matrix, op )
            setattr( self.matrix, op, functools.partial(self._operate, forward_operator=op))
    
    def __exit__(self, type, value, tb):
        for op in NumpyOverflowPreventer.inverse_operator.keys():
            setattr( self.matrix, op, self.originals[ op ] )

running this:

a= np.matrix(255, dtype= np.uint8)
b= np.matrix(255, dtype= np.uint8)
with NumpyOverflowPreventer(a):
    a+=1
with NumpyOverflowPreventer(b):
    b.__iadd__(1)
print a,b

returns this:

[[0]] [[255]]
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-12T21:23:09+00:00Added an answer on June 12, 2026 at 9:23 pm

    The issue you are seeing is that the special built-in methods are not looked up on the instance. They are looked up on the matrix type. So replacing them on the instance will not cause them to be used indirectly.

    One way to achieve your goal is to instead make NumpyOverflowPreventer a wrapper for the operations you want to address…

    import numpy as np 
    import sys
    
    class NumpyOverflowPreventer(object):
    
        inverse_operator= { 
            '__iadd__': '__sub__', 
            '__isub__': '__add__', 
            '__imul__': '__div__', 
            '__idiv__': '__mul__'
        }
    
        def __init__(self, matrix):
            m = matrix
            assert m.dtype==np.uint8
            self.matrix = m
            self.lower_range = float(0)
            self.upper_range = float(2**8-1)
    
        def __iadd__(self, v):
            # dynamic way to get the name "__iadd__"
            self._operate(v, sys._getframe().f_code.co_name)
            return self
    
        def _operate(self, b, forward_operator):
            assert type(b) in (int, float)
            reverse_operator = self.inverse_operator[forward_operator]
            uro= getattr(self.upper_range, reverse_operator)
            lro= getattr(self.lower_range, reverse_operator)
            afo= getattr(self.matrix, forward_operator)
            overflows= self.matrix > uro( b )
            underflows= self.matrix < lro( b )
            afo( b )
            self.matrix[overflows]= self.upper_range
            self.matrix[underflows]= self.lower_range
    

    I have only defined __iadd__ here, and I am sure you could do all of them dynamically with some metaclass/decorator action…but I am keeping it simple.

    Usage:

    a = np.matrix(255, dtype= np.uint8)
    b = np.matrix(255, dtype= np.uint8)
    
    p = NumpyOverflowPreventer(a)
    p+=1
    
    p = NumpyOverflowPreventer(b)
    p.__iadd__(1)
    
    print a,b
    # [[255]] [[255]]
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have an object from a NSObject class that I call brand and has
I have a numpy array which came from a cv2.imread and so has dtype
I have a JSVGCanvas object from the Batik library from java. In my application,
I have a class A which instantiates an object from class B internally. That
I have a WCF Web Service which is referenced from a class library. After
I have an object which is coded in a .as file, let's call it
Or is it? I have a thread object from: Thread myThread = new Thread(pObject);
I have a stdClass object created from json_decode that won't return the right number
I have an object I'm trying to populate from another object (that is, iterate
I have a situation whereby a thread can retrieve an object from the db,

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.